git.iko.soy/rowtype-yoga/purescript-native
on golang help sign in
Merge pull request #708 from purescript/650
e84d52bPhil Freeman
purescript.cabal+38−33
@@ -1,7 +1,7 @@
1name: purescript
1name: purescript
2version: 0.6.0.2
2version: 0.6.0.2
3cabal-version: >=1.8
3cabal-version: >=1.8
4−build-type: Simple
4+build-type: Simple
5license: MIT
5license: MIT
6license-file: LICENSE
6license-file: LICENSE
7copyright: (c) 2013-14 Phil Freeman, (c) 2014 Gary Burgess, and other contributors
7copyright: (c) 2013-14 Phil Freeman, (c) 2014 Gary Burgess, and other contributors
@@ -24,54 +24,42 @@ source-repository head
24 location: https://github.com/purescript/purescript.git
24 location: https://github.com/purescript/purescript.git
25
25
26library
26library
27− build-depends: base >=4 && <5,
27+ build-depends: base >=4 && <5,
28− cmdtheline == 0.2.*,
28+ cmdtheline == 0.2.*,
29− containers -any,
29+ containers -any,
30 unordered-containers -any,
30 unordered-containers -any,
31− directory >= 1.2,
31+ directory >= 1.2,
32− filepath -any,
32+ filepath -any,
33− mtl >= 2.1.0 && < 2.3.0,
33+ mtl >= 2.1.0 && < 2.3.0,
34 parsec -any,
34 parsec -any,
35− transformers >= 0.3 && < 0.5,
35+ transformers >= 0.3 && < 0.5,
36 utf8-string -any,
36 utf8-string -any,
37 pattern-arrows >= 0.0.2 && < 0.1,
37 pattern-arrows >= 0.0.2 && < 0.1,
38− monad-unify >= 0.2.2 && < 0.3,
38+ monad-unify >= 0.2.2 && < 0.3,
39 file-embed >= 0.0.7 && < 0.0.8,
39 file-embed >= 0.0.7 && < 0.0.8,
40 time -any
40 time -any
41 exposed-modules: Language.PureScript
41 exposed-modules: Language.PureScript
42+ Language.PureScript.CodeGen
43+ Language.PureScript.CodeGen.Common
44+ Language.PureScript.CodeGen.Externs
45+ Language.PureScript.CodeGen.JS
46+ Language.PureScript.CodeGen.JS.AST
42 Language.PureScript.Constants
47 Language.PureScript.Constants
43− Language.PureScript.Options
48+ Language.PureScript.DeadCodeElimination
44 Language.PureScript.Declarations
49 Language.PureScript.Declarations
45 Language.PureScript.Environment
50 Language.PureScript.Environment
46 Language.PureScript.Errors
51 Language.PureScript.Errors
47 Language.PureScript.Kinds
52 Language.PureScript.Kinds
48− Language.PureScript.Names
49− Language.PureScript.Supply
50− Language.PureScript.Types
51− Language.PureScript.Traversals
52− Language.PureScript.TypeClassDictionaries
53− Language.PureScript.DeadCodeElimination
54− Language.PureScript.Sugar
55 Language.PureScript.ModuleDependencies
53 Language.PureScript.ModuleDependencies
56− Language.PureScript.Sugar.CaseDeclarations
54+ Language.PureScript.Names
57− Language.PureScript.Sugar.DoNotation
58− Language.PureScript.Sugar.TypeDeclarations
59− Language.PureScript.Sugar.BindingGroups
60− Language.PureScript.Sugar.Operators
61− Language.PureScript.Sugar.TypeClasses
62− Language.PureScript.Sugar.Names
63− Language.PureScript.CodeGen
64− Language.PureScript.CodeGen.Common
65− Language.PureScript.CodeGen.Externs
66− Language.PureScript.CodeGen.JS
67− Language.PureScript.CodeGen.JS.AST
68 Language.PureScript.Optimizer
55 Language.PureScript.Optimizer
56+ Language.PureScript.Optimizer.Blocks
69 Language.PureScript.Optimizer.Common
57 Language.PureScript.Optimizer.Common
58+ Language.PureScript.Optimizer.Inliner
70 Language.PureScript.Optimizer.MagicDo
59 Language.PureScript.Optimizer.MagicDo
71 Language.PureScript.Optimizer.TCO
60 Language.PureScript.Optimizer.TCO
72− Language.PureScript.Optimizer.Inliner
73 Language.PureScript.Optimizer.Unused
61 Language.PureScript.Optimizer.Unused
74− Language.PureScript.Optimizer.Blocks
62+ Language.PureScript.Options
75 Language.PureScript.Parser
63 Language.PureScript.Parser
76 Language.PureScript.Parser.Common
64 Language.PureScript.Parser.Common
77 Language.PureScript.Parser.Declarations
65 Language.PureScript.Parser.Declarations
@@ -85,11 +73,28 @@ library
85 Language.PureScript.Pretty.Types
73 Language.PureScript.Pretty.Types
86 Language.PureScript.Pretty.Values
74 Language.PureScript.Pretty.Values
87 Language.PureScript.Renamer
75 Language.PureScript.Renamer
76+ Language.PureScript.Sugar
77+ Language.PureScript.Sugar.BindingGroups
78+ Language.PureScript.Sugar.CaseDeclarations
79+ Language.PureScript.Sugar.DoNotation
80+ Language.PureScript.Sugar.Names
81+ Language.PureScript.Sugar.Operators
82+ Language.PureScript.Sugar.TypeClasses
83+ Language.PureScript.Sugar.TypeDeclarations
84+ Language.PureScript.Supply
85+ Language.PureScript.Traversals
88 Language.PureScript.TypeChecker
86 Language.PureScript.TypeChecker
87+ Language.PureScript.TypeChecker.Entailment
89 Language.PureScript.TypeChecker.Kinds
88 Language.PureScript.TypeChecker.Kinds
90 Language.PureScript.TypeChecker.Monad
89 Language.PureScript.TypeChecker.Monad
90+ Language.PureScript.TypeChecker.Rows
91+ Language.PureScript.TypeChecker.Skolems
92+ Language.PureScript.TypeChecker.Subsumption
91 Language.PureScript.TypeChecker.Synonyms
93 Language.PureScript.TypeChecker.Synonyms
92 Language.PureScript.TypeChecker.Types
94 Language.PureScript.TypeChecker.Types
95+ Language.PureScript.TypeChecker.Unify
96+ Language.PureScript.TypeClassDictionaries
97+ Language.PureScript.Types
93 exposed: True
98 exposed: True
94 buildable: True
99 buildable: True
95 hs-source-dirs: src
100 hs-source-dirs: src
@@ -128,12 +133,12 @@ executable psci
128 Parser
133 Parser
129 ghc-options: -Wall -O2
134 ghc-options: -Wall -O2
130
135
131−executable psc-docs
136+executable psc-docs
132 build-depends: base >=4 && <5, cmdtheline -any, purescript -any, utf8-string -any,
137 build-depends: base >=4 && <5, cmdtheline -any, purescript -any, utf8-string -any,
133 process -any, mtl -any
138 process -any, mtl -any
134 main-is: Main.hs
139 main-is: Main.hs
135 buildable: True
140 buildable: True
136− hs-source-dirs: psc-docs
141+ hs-source-dirs: psc-docs
137 other-modules:
142 other-modules:
138 ghc-options: -Wall -O2
143 ghc-options: -Wall -O2
139
144
src/Language/PureScript/TypeChecker/Entailment.hsnew file+217
@@ -0,0 +1,217 @@
1+-----------------------------------------------------------------------------
2+--
3+-- Module : Language.PureScript.TypeChecker.Entailment
4+-- Copyright : (c) Phil Freeman 2013
5+-- License : MIT
6+--
7+-- Maintainer : Phil Freeman <paf31@cantab.net>
8+-- Stability : experimental
9+-- Portability :
10+--
11+-- |
12+-- Type class entailment
13+--
14+-----------------------------------------------------------------------------
15+
16+module Language.PureScript.TypeChecker.Entailment (
17+ entails
18+) where
19+
20+import Data.Function (on)
21+import Data.List
22+import Data.Maybe (maybeToList)
23+import qualified Data.Map as M
24+
25+import Control.Applicative
26+import Control.Arrow (Arrow(..))
27+import Control.Monad.Error
28+
29+import Language.PureScript.Declarations
30+import Language.PureScript.Environment
31+import Language.PureScript.Names
32+import Language.PureScript.Pretty
33+import Language.PureScript.TypeChecker.Monad
34+import Language.PureScript.TypeChecker.Synonyms
35+import Language.PureScript.TypeChecker.Unify
36+import Language.PureScript.TypeClassDictionaries
37+import Language.PureScript.Types
38+import qualified Language.PureScript.Constants as C
39+
40+-- |
41+-- A simplified representation of expressions which are used to represent type
42+-- class dictionaries at runtime, which can be compared for equality
43+--
44+data DictionaryValue
45+ -- |
46+ -- A dictionary which is brought into scope by a local constraint
47+ --
48+ = LocalDictionaryValue (Qualified Ident)
49+ -- |
50+ -- A dictionary which is brought into scope by an instance declaration
51+ --
52+ | GlobalDictionaryValue (Qualified Ident)
53+ -- |
54+ -- A dictionary which depends on other dictionaries
55+ --
56+ | DependentDictionaryValue (Qualified Ident) [DictionaryValue]
57+ -- |
58+ -- A subclass dictionary
59+ --
60+ | SubclassDictionaryValue DictionaryValue (Qualified ProperName) Integer
61+ deriving (Show, Ord, Eq)
62+
63+-- |
64+-- Check that the current set of type class dictionaries entail the specified type class goal, and, if so,
65+-- return a type class dictionary reference.
66+--
67+entails :: Environment -> ModuleName -> [TypeClassDictionaryInScope] -> (Qualified ProperName, [Type]) -> Bool -> Check Expr
68+entails env moduleName context = solve (sortedNubBy canonicalizeDictionary (filter filterModule context))
69+ where
70+ sortedNubBy :: (Ord k) => (v -> k) -> [v] -> [v]
71+ sortedNubBy f vs = M.elems (M.fromList (map (f &&& id) vs))
72+
73+ -- Filter out type dictionaries which are in scope in the current module
74+ filterModule :: TypeClassDictionaryInScope -> Bool
75+ filterModule (TypeClassDictionaryInScope { tcdName = Qualified (Just mn) _ }) | mn == moduleName = True
76+ filterModule (TypeClassDictionaryInScope { tcdName = Qualified Nothing _ }) = True
77+ filterModule _ = False
78+
79+ solve context' (className, tys) trySuperclasses =
80+ checkOverlaps $ go trySuperclasses className tys
81+ where
82+ go trySuperclasses' className' tys' =
83+ -- Look for regular type instances
84+ [ mkDictionary (canonicalizeDictionary tcd) args
85+ | tcd <- context'
86+ -- Make sure the type class name matches the one we are trying to satisfy
87+ , className' == tcdClassName tcd
88+ -- Make sure the type unifies with the type in the type instance definition
89+ , subst <- maybeToList . (>>= verifySubstitution) . fmap concat $ zipWithM (typeHeadsAreEqual moduleName env) tys' (tcdInstanceTypes tcd)
90+ -- Solve any necessary subgoals
91+ , args <- solveSubgoals subst (tcdDependencies tcd) ] ++
92+
93+ -- Look for implementations via superclasses
94+ [ SubclassDictionaryValue suDict superclass index
95+ | trySuperclasses'
96+ , (subclassName, (args, _, implies)) <- M.toList (typeClasses env)
97+ -- Try each superclass
98+ , (index, (superclass, suTyArgs)) <- zip [0..] implies
99+ -- Make sure the type class name matches the superclass name
100+ , className' == superclass
101+ -- Make sure the types unify with the types in the superclass implication
102+ , subst <- maybeToList . (>>= verifySubstitution) . fmap concat $ zipWithM (typeHeadsAreEqual moduleName env) tys' suTyArgs
103+ -- Finally, satisfy the subclass constraint
104+ , args' <- maybeToList $ mapM ((`lookup` subst) . fst) args
105+ , suDict <- go True subclassName args' ]
106+
107+ -- Create dictionaries for subgoals which still need to be solved by calling go recursively
108+ -- E.g. the goal (Show a, Show b) => Show (Either a b) can be satisfied if the current type
109+ -- unifies with Either a b, and we can satisfy the subgoals Show a and Show b recursively.
110+ solveSubgoals :: [(String, Type)] -> Maybe [(Qualified ProperName, [Type])] -> [Maybe [DictionaryValue]]
111+ solveSubgoals _ Nothing = return Nothing
112+ solveSubgoals subst (Just subgoals) = do
113+ dict <- mapM (uncurry (go True) . second (map (replaceAllTypeVars subst))) subgoals
114+ return $ Just dict
115+ -- Make a dictionary from subgoal dictionaries by applying the correct function
116+ mkDictionary :: Qualified Ident -> Maybe [DictionaryValue] -> DictionaryValue
117+ mkDictionary fnName Nothing = LocalDictionaryValue fnName
118+ mkDictionary fnName (Just []) = GlobalDictionaryValue fnName
119+ mkDictionary fnName (Just dicts) = DependentDictionaryValue fnName dicts
120+ -- Turn a DictionaryValue into a Expr
121+ dictionaryValueToValue :: DictionaryValue -> Expr
122+ dictionaryValueToValue (LocalDictionaryValue fnName) = Var fnName
123+ dictionaryValueToValue (GlobalDictionaryValue fnName) = Var fnName
124+ dictionaryValueToValue (DependentDictionaryValue fnName dicts) = foldl App (Var fnName) (map dictionaryValueToValue dicts)
125+ dictionaryValueToValue (SubclassDictionaryValue dict superclassName index) =
126+ App (Accessor (C.__superclass_ ++ show superclassName ++ "_" ++ show index)
127+ (dictionaryValueToValue dict))
128+ valUndefined
129+ -- Ensure that a substitution is valid
130+ verifySubstitution :: [(String, Type)] -> Maybe [(String, Type)]
131+ verifySubstitution subst = do
132+ let grps = groupBy ((==) `on` fst) subst
133+ guard (all (pairwise (unifiesWith env) . map snd) grps)
134+ return $ map head grps
135+ -- |
136+ -- Check for overlapping instances
137+ --
138+ checkOverlaps :: [DictionaryValue] -> Check Expr
139+ checkOverlaps dicts =
140+ case [ (d1, d2) | d1 <- dicts, d2 <- dicts, d1 `overlapping` d2 ] of
141+ (d1, d2) : _ -> throwError . strMsg $ unlines
142+ [ "Overlapping instances found for " ++ show className ++ " " ++ unwords (map prettyPrintType tys) ++ "."
143+ , "For example:"
144+ , prettyPrintDictionaryValue d1
145+ , "and:"
146+ , prettyPrintDictionaryValue d2
147+ ]
148+ _ -> case chooseSimplestDictionaries dicts of
149+ [] -> throwError . strMsg $
150+ "No instance found for " ++ show className ++ " " ++ unwords (map prettyPrintTypeAtom tys)
151+ d : _ -> return $ dictionaryValueToValue d
152+ -- Choose the simplest DictionaryValues from a list of candidates
153+ -- The reason for this function is as follows:
154+ -- When considering overlapping instances, we don't want to consider the same dictionary
155+ -- to be an overlap of itself when obtained as a superclass of another class.
156+ -- Observing that we probably don't want to select a superclass instance when an instance
157+ -- is available directly, and that there is no way for a superclass instance to actually
158+ -- introduce an overlap that wouldn't have been there already, we simply remove dictionaries
159+ -- obtained as superclass instances if there are simpler instances available.
160+ chooseSimplestDictionaries :: [DictionaryValue] -> [DictionaryValue]
161+ chooseSimplestDictionaries ds = case filter isSimpleDictionaryValue ds of
162+ [] -> ds
163+ simple -> simple
164+ isSimpleDictionaryValue SubclassDictionaryValue{} = False
165+ isSimpleDictionaryValue (DependentDictionaryValue _ ds) = all isSimpleDictionaryValue ds
166+ isSimpleDictionaryValue _ = True
167+ -- |
168+ -- Check if two dictionaries are overlapping
169+ --
170+ -- Dictionaries which are subclass dictionaries cannot overlap, since otherwise the overlap would have
171+ -- been caught when constructing superclass dictionaries.
172+ --
173+ overlapping :: DictionaryValue -> DictionaryValue -> Bool
174+ overlapping (LocalDictionaryValue nm1) (LocalDictionaryValue nm2) | nm1 == nm2 = False
175+ overlapping (GlobalDictionaryValue nm1) (GlobalDictionaryValue nm2) | nm1 == nm2 = False
176+ overlapping (DependentDictionaryValue nm1 ds1) (DependentDictionaryValue nm2 ds2)
177+ | nm1 == nm2 = or $ zipWith overlapping ds1 ds2
178+ overlapping SubclassDictionaryValue{} _ = False
179+ overlapping _ SubclassDictionaryValue{} = False
180+ overlapping _ _ = True
181+ -- |
182+ -- Render a DictionaryValue fit for human consumption in error messages
183+ --
184+ prettyPrintDictionaryValue :: DictionaryValue -> String
185+ prettyPrintDictionaryValue = unlines . indented 0
186+ where
187+ indented n (LocalDictionaryValue _) = [spaces n ++ "Dictionary in scope"]
188+ indented n (GlobalDictionaryValue nm) = [spaces n ++ show nm]
189+ indented n (DependentDictionaryValue nm args) = (spaces n ++ show nm ++ " via") : concatMap (indented (n + 2)) args
190+ indented n (SubclassDictionaryValue sup nm _) = (spaces n ++ show nm ++ " via superclass") : indented (n + 2) sup
191+
192+ spaces n = replicate n ' ' ++ "- "
193+
194+ valUndefined :: Expr
195+ valUndefined = Var (Qualified (Just (ModuleName [ProperName C.prim])) (Ident C.undefined))
196+
197+-- |
198+-- Check whether the type heads of two types are equal (for the purposes of type class dictionary lookup),
199+-- and return a substitution from type variables to types which makes the type heads unify.
200+--
201+typeHeadsAreEqual :: ModuleName -> Environment -> Type -> Type -> Maybe [(String, Type)]
202+typeHeadsAreEqual _ _ (Skolem _ s1 _) (Skolem _ s2 _) | s1 == s2 = Just []
203+typeHeadsAreEqual _ _ t (TypeVar v) = Just [(v, t)]
204+typeHeadsAreEqual _ _ (TypeConstructor c1) (TypeConstructor c2) | c1 == c2 = Just []
205+typeHeadsAreEqual m e (TypeApp h1 t1) (TypeApp h2 t2) = (++) <$> typeHeadsAreEqual m e h1 h2 <*> typeHeadsAreEqual m e t1 t2
206+typeHeadsAreEqual m e (SaturatedTypeSynonym name args) t2 = case expandTypeSynonym' e name args of
207+ Left _ -> Nothing
208+ Right t1 -> typeHeadsAreEqual m e t1 t2
209+typeHeadsAreEqual _ _ _ _ = Nothing
210+
211+-- |
212+-- Check all values in a list pairwise match a predicate
213+--
214+pairwise :: (a -> a -> Bool) -> [a] -> Bool
215+pairwise _ [] = True
216+pairwise _ [_] = True
217+pairwise p (x : xs) = all (p x) xs && pairwise p xs
src/Language/PureScript/TypeChecker/Kinds.hs+18−23
@@ -22,23 +22,23 @@ module Language.PureScript.TypeChecker.Kinds (
22 kindsOfAll
22 kindsOfAll
23) where
23) where
24
24
25−import Language.PureScript.Types
25+import Data.Maybe (fromMaybe)
26−import Language.PureScript.Kinds
26+import Data.Monoid ((<>))
27−import Language.PureScript.Names
27+import qualified Data.HashMap.Strict as H
28−import Language.PureScript.TypeChecker.Monad
28+import qualified Data.Map as M
29−import Language.PureScript.Pretty
30−import Language.PureScript.Environment
31−import Language.PureScript.Errors
32
29
33−import Control.Monad.State
30+import Control.Applicative
34import Control.Monad.Error
31import Control.Monad.Error
32+import Control.Monad.State
35import Control.Monad.Unify
33import Control.Monad.Unify
36
34
37−import Control.Applicative
35+import Language.PureScript.Environment
38−
36+import Language.PureScript.Errors
39−import qualified Data.Map as M
37+import Language.PureScript.Kinds
40−import qualified Data.HashMap.Strict as H
38+import Language.PureScript.Names
41−import Data.Monoid ((<>))
39+import Language.PureScript.Pretty
40+import Language.PureScript.TypeChecker.Monad
41+import Language.PureScript.Types
42
42
43instance Partial Kind where
43instance Partial Kind where
44 unknown = KUnknown
44 unknown = KUnknown
@@ -50,9 +50,7 @@ instance Partial Kind where
50 go _ = []
50 go _ = []
51 ($?) sub = everywhereOnKinds go
51 ($?) sub = everywhereOnKinds go
52 where
52 where
53− go t@(KUnknown u) = case H.lookup u (runSubstitution sub) of
53+ go t@(KUnknown u) = fromMaybe t $ H.lookup u (runSubstitution sub)
54− Nothing -> t
55− Just t' -> t'
56 go other = other
54 go other = other
57
55
58instance Unifiable Check Kind where
56instance Unifiable Check Kind where
@@ -85,12 +83,12 @@ kindsOf isData moduleName name args ts = fmap tidyUp . liftUnify $ do
85 tyCon <- fresh
83 tyCon <- fresh
86 kargs <- replicateM (length args) fresh
84 kargs <- replicateM (length args) fresh
87 rest <- zipWithM freshKindVar args kargs
85 rest <- zipWithM freshKindVar args kargs
88− let dict = (name, tyCon) : rest
86+ let dict = (name, tyCon) : rest
89 bindLocalTypeVariables moduleName dict $
87 bindLocalTypeVariables moduleName dict $
90 solveTypes isData ts kargs tyCon
88 solveTypes isData ts kargs tyCon
91 where
89 where
92 tidyUp (k, sub) = starIfUnknown $ sub $? k
90 tidyUp (k, sub) = starIfUnknown $ sub $? k
93−
91+
94freshKindVar :: (String, Maybe Kind) -> Kind -> UnifyT Kind Check (ProperName, Kind)
92freshKindVar :: (String, Maybe Kind) -> Kind -> UnifyT Kind Check (ProperName, Kind)
95freshKindVar (arg, Nothing) kind = return (ProperName arg, kind)
93freshKindVar (arg, Nothing) kind = return (ProperName arg, kind)
96freshKindVar (arg, Just kind') kind = do
94freshKindVar (arg, Just kind') kind = do
@@ -125,13 +123,13 @@ kindsOfAll moduleName syns tys = fmap tidyUp . liftUnify $ do
125-- |
123-- |
126-- Solve the set of kind constraints associated with the data constructors for a type constructor
124-- Solve the set of kind constraints associated with the data constructors for a type constructor
127--
125--
128−solveTypes :: Bool -> [Type] -> [Kind] -> Kind -> UnifyT Kind (Check) Kind
126+solveTypes :: Bool -> [Type] -> [Kind] -> Kind -> UnifyT Kind Check Kind
129solveTypes isData ts kargs tyCon = do
127solveTypes isData ts kargs tyCon = do
130 ks <- mapM infer ts
128 ks <- mapM infer ts
131 when isData $ do
129 when isData $ do
132 tyCon =?= foldr FunKind Star kargs
130 tyCon =?= foldr FunKind Star kargs
133 forM_ ks $ \k -> k =?= Star
131 forM_ ks $ \k -> k =?= Star
134− when (not isData) $ do
132+ unless isData $
135 tyCon =?= foldr FunKind (head ks) kargs
133 tyCon =?= foldr FunKind (head ks) kargs
136 return tyCon
134 return tyCon
137
135
@@ -191,6 +189,3 @@ infer' (KindedType ty k) = do
191 k =?= k'
189 k =?= k'
192 return k'
190 return k'
193infer' _ = error "Invalid argument to infer"
191infer' _ = error "Invalid argument to infer"
194−
195−
196−
src/Language/PureScript/TypeChecker/Monad.hs+10−11
@@ -18,23 +18,22 @@
18
18
19module Language.PureScript.TypeChecker.Monad where
19module Language.PureScript.TypeChecker.Monad where
20
20
21−import Language.PureScript.Types
22−import Language.PureScript.Kinds
23−import Language.PureScript.Names
24−import Language.PureScript.Declarations (canonicalizeDictionary)
25−import Language.PureScript.Environment
26−import Language.PureScript.TypeClassDictionaries
27−import Language.PureScript.Options
28−import Language.PureScript.Errors
29−
30import Data.Maybe
21import Data.Maybe
22+import qualified Data.Map as M
31
23
32import Control.Applicative
24import Control.Applicative
33−import Control.Monad.State
34import Control.Monad.Error
25import Control.Monad.Error
26+import Control.Monad.State
35import Control.Monad.Unify
27import Control.Monad.Unify
36
28
37−import qualified Data.Map as M
29+import Language.PureScript.Declarations (canonicalizeDictionary)
30+import Language.PureScript.Environment
31+import Language.PureScript.Errors
32+import Language.PureScript.Kinds
33+import Language.PureScript.Names
34+import Language.PureScript.Options
35+import Language.PureScript.TypeClassDictionaries
36+import Language.PureScript.Types
38
37
39-- |
38-- |
40-- Temporarily bind a collection of names to values
39-- Temporarily bind a collection of names to values
src/Language/PureScript/TypeChecker/Rows.hsnew file+66
@@ -0,0 +1,66 @@
1+-----------------------------------------------------------------------------
2+--
3+-- Module : Language.PureScript.TypeChecker.Rows
4+-- Copyright : (c) Phil Freeman 2013
5+-- License : MIT
6+--
7+-- Maintainer : Phil Freeman <paf31@cantab.net>
8+-- Stability : experimental
9+-- Portability :
10+--
11+-- |
12+-- Functions relating to type checking for rows
13+--
14+-----------------------------------------------------------------------------
15+
16+module Language.PureScript.TypeChecker.Rows (
17+ checkDuplicateLabels
18+) where
19+
20+import Data.List
21+
22+import Control.Monad.Error
23+
24+import Language.PureScript.Declarations
25+import Language.PureScript.Errors
26+import Language.PureScript.TypeChecker.Monad
27+import Language.PureScript.Types
28+
29+-- |
30+-- Ensure rows do not contain duplicate labels
31+--
32+checkDuplicateLabels :: Expr -> Check ()
33+checkDuplicateLabels =
34+ let (_, f, _) = everywhereOnValuesM def go def
35+ in void . f
36+ where
37+ def :: a -> Check a
38+ def = return
39+
40+ go :: Expr -> Check Expr
41+ go e@(TypedValue _ val ty) = do
42+ checkDups ty
43+ return e
44+
45+ where
46+ checkDups :: Type -> Check ()
47+ checkDups (TypeApp t1 t2) = checkDups t1 >> checkDups t2
48+ checkDups (SaturatedTypeSynonym _ ts) = mapM_ checkDups ts
49+ checkDups (ForAll _ t _) = checkDups t
50+ checkDups (ConstrainedType args t) = do
51+ mapM_ checkDups $ concatMap snd args
52+ checkDups t
53+ checkDups r@RCons{} =
54+ let (ls, _) = rowToList r in
55+ case firstDup . sort . map fst $ ls of
56+ Just l -> throwError $ mkErrorStack ("Duplicate label " ++ show l ++ " in row") $ Just (ExprError val)
57+ Nothing -> return ()
58+ checkDups _ = return ()
59+
60+ firstDup :: (Eq a) => [a] -> Maybe a
61+ firstDup (x : xs@(x' : _))
62+ | x == x' = Just x
63+ | otherwise = firstDup xs
64+ firstDup _ = Nothing
65+
66+ go other = return other
src/Language/PureScript/TypeChecker/Skolems.hsnew file+114
@@ -0,0 +1,114 @@
1+-----------------------------------------------------------------------------
2+--
3+-- Module : Language.PureScript.TypeChecker.Skolems
4+-- Copyright : (c) Phil Freeman 2013
5+-- License : MIT
6+--
7+-- Maintainer : Phil Freeman <paf31@cantab.net>
8+-- Stability : experimental
9+-- Portability :
10+--
11+-- |
12+-- Functions relating to skolemization used during typechecking
13+--
14+-----------------------------------------------------------------------------
15+
16+module Language.PureScript.TypeChecker.Skolems (
17+ newSkolemConstant,
18+ introduceSkolemScope,
19+ newSkolemScope,
20+ skolemize,
21+ skolemizeTypesInValue,
22+ skolemEscapeCheck
23+) where
24+
25+import Data.List (nub, (\\))
26+import Data.Monoid
27+
28+import Control.Applicative
29+import Control.Monad.Error
30+import Control.Monad.Unify
31+
32+import Language.PureScript.Declarations
33+import Language.PureScript.Errors
34+import Language.PureScript.Pretty
35+import Language.PureScript.TypeChecker.Monad
36+import Language.PureScript.Types
37+
38+-- |
39+-- Generate a new skolem constant
40+--
41+newSkolemConstant :: UnifyT Type Check Int
42+newSkolemConstant = fresh'
43+
44+-- |
45+-- Introduce skolem scope at every occurence of a ForAll
46+--
47+introduceSkolemScope :: Type -> UnifyT Type Check Type
48+introduceSkolemScope = everywhereOnTypesM go
49+ where
50+ go (ForAll ident ty Nothing) = ForAll ident ty <$> (Just <$> newSkolemScope)
51+ go other = return other
52+
53+-- |
54+-- Generate a new skolem scope
55+--
56+newSkolemScope :: UnifyT Type Check SkolemScope
57+newSkolemScope = SkolemScope <$> fresh'
58+
59+-- |
60+-- Skolemize a type variable by replacing its instances with fresh skolem constants
61+--
62+skolemize :: String -> Int -> SkolemScope -> Type -> Type
63+skolemize ident sko scope = replaceTypeVars ident (Skolem ident sko scope)
64+
65+-- |
66+-- This function has one purpose - to skolemize type variables appearing in a
67+-- SuperClassDictionary placeholder. These type variables are somewhat unique since they are the
68+-- only example of scoped type variables.
69+--
70+skolemizeTypesInValue :: String -> Int -> SkolemScope -> Expr -> Expr
71+skolemizeTypesInValue ident sko scope = let (_, f, _) = everywhereOnValues id go id in f
72+ where
73+ go (SuperClassDictionary c ts) = SuperClassDictionary c (map (skolemize ident sko scope) ts)
74+ go other = other
75+
76+-- |
77+-- Ensure skolem variables do not escape their scope
78+--
79+skolemEscapeCheck :: Expr -> Check ()
80+skolemEscapeCheck (TypedValue False _ _) = return ()
81+skolemEscapeCheck root@TypedValue{} =
82+ -- Every skolem variable is created when a ForAll type is skolemized.
83+ -- This determines the scope of that skolem variable, which is copied from the SkolemScope
84+ -- field of the ForAll constructor.
85+ -- We traverse the tree top-down, and collect any SkolemScopes introduced by ForAlls.
86+ -- If a Skolem is encountered whose SkolemScope is not in the current list, we have found
87+ -- an escaped skolem variable.
88+ let (_, f, _, _, _) = everythingWithContextOnValues [] [] (++) def go def def def
89+ in case f root of
90+ [] -> return ()
91+ ((binding, val) : _) -> throwError $ mkErrorStack ("Rigid/skolem type variable " ++ maybe "" (("bound by " ++) . prettyPrintValue) binding ++ " has escaped.") (Just (ExprError val))
92+ where
93+ def s _ = (s, [])
94+
95+ go :: [(SkolemScope, Expr)] -> Expr -> ([(SkolemScope, Expr)], [(Maybe Expr, Expr)])
96+ go scos val@(TypedValue _ _ (ForAll _ _ (Just sco))) = ((sco, val) : scos, [])
97+ go scos val@(TypedValue _ _ ty) = case collectSkolems ty \\ map fst scos of
98+ (sco : _) -> (scos, [(findBindingScope sco, val)])
99+ _ -> (scos, [])
100+ where
101+ collectSkolems :: Type -> [SkolemScope]
102+ collectSkolems = nub . everythingOnTypes (++) collect
103+ where
104+ collect (Skolem _ _ scope) = [scope]
105+ collect _ = []
106+ go scos _ = (scos, [])
107+ findBindingScope :: SkolemScope -> Maybe Expr
108+ findBindingScope sco =
109+ let (_, f, _, _, _) = everythingOnValues mappend (const mempty) go' (const mempty) (const mempty) (const mempty)
110+ in getFirst $ f root
111+ where
112+ go' val@(TypedValue _ _ (ForAll _ _ (Just sco'))) | sco == sco' = First (Just val)
113+ go' _ = mempty
114+skolemEscapeCheck val = throwError $ mkErrorStack "Untyped value passed to skolemEscapeCheck" (Just (ExprError val))
src/Language/PureScript/TypeChecker/Subsumption.hsnew file+103
@@ -0,0 +1,103 @@
1+-----------------------------------------------------------------------------
2+--
3+-- Module : Language.PureScript.TypeChecker.Subsumption
4+-- Copyright : (c) Phil Freeman 2013
5+-- License : MIT
6+--
7+-- Maintainer : Phil Freeman <paf31@cantab.net>
8+-- Stability : experimental
9+-- Portability :
10+--
11+-- |
12+-- Subsumption checking
13+--
14+-----------------------------------------------------------------------------
15+
16+module Language.PureScript.TypeChecker.Subsumption (
17+ subsumes
18+) where
19+
20+import Data.List (sortBy)
21+import Data.Monoid
22+import Data.Ord (comparing)
23+
24+import Control.Applicative
25+import Control.Monad.Error
26+import Control.Monad.Unify
27+
28+import Language.PureScript.Declarations
29+import Language.PureScript.Environment
30+import Language.PureScript.Errors
31+import Language.PureScript.Pretty
32+import Language.PureScript.TypeChecker.Monad
33+import Language.PureScript.TypeChecker.Skolems
34+import Language.PureScript.TypeChecker.Synonyms
35+import Language.PureScript.TypeChecker.Unify
36+import Language.PureScript.Types
37+
38+-- |
39+-- Check whether one type subsumes another, rethrowing errors to provide a better error message
40+--
41+subsumes :: Maybe Expr -> Type -> Type -> UnifyT Type Check (Maybe Expr)
42+subsumes val ty1 ty2 = rethrow (mkErrorStack errorMessage (ExprError <$> val) <>) $ subsumes' val ty1 ty2
43+ where
44+ errorMessage = "Error checking that type "
45+ ++ prettyPrintType ty1
46+ ++ " subsumes type "
47+ ++ prettyPrintType ty2
48+
49+-- |
50+-- Check whether one type subsumes another
51+--
52+subsumes' :: Maybe Expr -> Type -> Type -> UnifyT Type Check (Maybe Expr)
53+subsumes' val (ForAll ident ty1 _) ty2 = do
54+ replaced <- replaceVarWithUnknown ident ty1
55+ subsumes val replaced ty2
56+subsumes' val ty1 (ForAll ident ty2 sco) =
57+ case sco of
58+ Just sco' -> do
59+ sko <- newSkolemConstant
60+ let sk = skolemize ident sko sco' ty2
61+ subsumes val ty1 sk
62+ Nothing -> throwError . strMsg $ "Skolem variable scope is unspecified"
63+subsumes' val (TypeApp (TypeApp f1 arg1) ret1) (TypeApp (TypeApp f2 arg2) ret2) | f1 == tyFunction && f2 == tyFunction = do
64+ _ <- subsumes Nothing arg2 arg1
65+ _ <- subsumes Nothing ret1 ret2
66+ return val
67+subsumes' val (SaturatedTypeSynonym name tyArgs) ty2 = do
68+ ty1 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
69+ subsumes val ty1 ty2
70+subsumes' val ty1 (SaturatedTypeSynonym name tyArgs) = do
71+ ty2 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
72+ subsumes val ty1 ty2
73+subsumes' val (KindedType ty1 _) ty2 =
74+ subsumes val ty1 ty2
75+subsumes' val ty1 (KindedType ty2 _) =
76+ subsumes val ty1 ty2
77+subsumes' (Just val) (ConstrainedType constraints ty1) ty2 = do
78+ dicts <- getTypeClassDictionaries
79+ subsumes' (Just $ foldl App val (map (flip (TypeClassDictionary True) dicts) constraints)) ty1 ty2
80+subsumes' val (TypeApp f1 r1) (TypeApp f2 r2) | f1 == tyObject && f2 == tyObject = do
81+ let
82+ (ts1, r1') = rowToList r1
83+ (ts2, r2') = rowToList r2
84+ ts1' = sortBy (comparing fst) ts1
85+ ts2' = sortBy (comparing fst) ts2
86+ go ts1' ts2' r1' r2'
87+ return val
88+ where
89+ go [] ts2 r1' r2' = r1' =?= rowFromList (ts2, r2')
90+ go ts1 [] r1' r2' = r2' =?= rowFromList (ts1, r1')
91+ go ((p1, ty1) : ts1) ((p2, ty2) : ts2) r1' r2'
92+ | p1 == p2 = do _ <- subsumes Nothing ty1 ty2
93+ go ts1 ts2 r1' r2'
94+ | p1 < p2 = do rest <- fresh
95+ r2' =?= RCons p1 ty1 rest
96+ go ts1 ((p2, ty2) : ts2) r1' rest
97+ | otherwise = do rest <- fresh
98+ r1' =?= RCons p2 ty2 rest
99+ go ((p1, ty1) : ts1) ts2 rest r2'
100+subsumes' val ty1 ty2@(TypeApp obj _) | obj == tyObject = subsumes val ty2 ty1
101+subsumes' val ty1 ty2 = do
102+ ty1 =?= ty2
103+ return val
src/Language/PureScript/TypeChecker/Synonyms.hs+61−6
@@ -13,17 +13,28 @@
13--
13--
14-----------------------------------------------------------------------------
14-----------------------------------------------------------------------------
15
15
16+{-# LANGUAGE FlexibleContexts, MultiParamTypeClasses #-}
17+
16module Language.PureScript.TypeChecker.Synonyms (
18module Language.PureScript.TypeChecker.Synonyms (
17− saturateAllTypeSynonyms
19+ saturateAllTypeSynonyms,
20+ desaturateAllTypeSynonyms,
21+ replaceAllTypeSynonyms,
22+ expandAllTypeSynonyms,
23+ expandTypeSynonym,
24+ expandTypeSynonym'
18) where
25) where
19
26
20−import Language.PureScript.Types
21−import Language.PureScript.Names
22−
23−import Control.Applicative ((<$>))
24import Data.Maybe (fromMaybe)
27import Data.Maybe (fromMaybe)
25−import Control.Monad.Writer
28+import qualified Data.Map as M
29+
30+import Control.Applicative
26import Control.Monad.Error
31import Control.Monad.Error
32+import Control.Monad.State
33+
34+import Language.PureScript.Environment
35+import Language.PureScript.Names
36+import Language.PureScript.TypeChecker.Monad
37+import Language.PureScript.Types
27
38
28-- |
39-- |
29-- Build a type substitution for a type synonym
40-- Build a type substitution for a type synonym
@@ -51,5 +62,49 @@ saturateTypeSynonym name n = everywhereOnTypesTopDownM replace
51saturateAllTypeSynonyms :: [(Qualified ProperName, Int)] -> Type -> Either String Type
62saturateAllTypeSynonyms :: [(Qualified ProperName, Int)] -> Type -> Either String Type
52saturateAllTypeSynonyms syns d = foldM (\result (name, n) -> saturateTypeSynonym name n result) d syns
63saturateAllTypeSynonyms syns d = foldM (\result (name, n) -> saturateTypeSynonym name n result) d syns
53
64
65+-- |
66+-- \"Desaturate\" @SaturatedTypeSynonym@s
67+--
68+desaturateAllTypeSynonyms :: Type -> Type
69+desaturateAllTypeSynonyms = everywhereOnTypes replaceSaturatedTypeSynonym
70+ where
71+ replaceSaturatedTypeSynonym (SaturatedTypeSynonym name args) = foldl TypeApp (TypeConstructor name) args
72+ replaceSaturatedTypeSynonym t = t
54
73
74+-- |
75+-- Replace fully applied type synonyms with the @SaturatedTypeSynonym@ data constructor, which helps generate
76+-- better error messages during unification.
77+--
78+replaceAllTypeSynonyms' :: Environment -> Type -> Either String Type
79+replaceAllTypeSynonyms' env d =
80+ let
81+ syns = map (\(name, (args, _)) -> (name, length args)) . M.toList $ typeSynonyms env
82+ in
83+ saturateAllTypeSynonyms syns d
55
84
85+replaceAllTypeSynonyms :: (Error e, Functor m, Monad m, MonadState CheckState m, MonadError e m) => Type -> m Type
86+replaceAllTypeSynonyms d = do
87+ env <- getEnv
88+ either (throwError . strMsg) return $ replaceAllTypeSynonyms' env d
89+
90+-- |
91+-- Replace a type synonym and its arguments with the aliased type
92+--
93+expandTypeSynonym' :: Environment -> Qualified ProperName -> [Type] -> Either String Type
94+expandTypeSynonym' env name args =
95+ case M.lookup name (typeSynonyms env) of
96+ Just (synArgs, body) -> do
97+ let repl = replaceAllTypeVars (zip (map fst synArgs) args) body
98+ replaceAllTypeSynonyms' env repl
99+ Nothing -> error "Type synonym was not defined"
100+
101+expandTypeSynonym :: (Error e, Functor m, Monad m, MonadState CheckState m, MonadError e m) => Qualified ProperName -> [Type] -> m Type
102+expandTypeSynonym name args = do
103+ env <- getEnv
104+ either (throwError . strMsg) return $ expandTypeSynonym' env name args
105+
106+expandAllTypeSynonyms :: (Error e, Functor m, Applicative m, Monad m, MonadState CheckState m, MonadError e m) => Type -> m Type
107+expandAllTypeSynonyms = everywhereOnTypesTopDownM go
108+ where
109+ go (SaturatedTypeSynonym name args) = expandTypeSynonym name args
110+ go other = return other
src/Language/PureScript/TypeChecker/Types.hs+39−591
@@ -13,10 +13,7 @@
13--
13--
14-----------------------------------------------------------------------------
14-----------------------------------------------------------------------------
15
15
16−{-# OPTIONS_GHC -fno-warn-orphans #-}
17−{-# LANGUAGE FlexibleInstances #-}
18−{-# LANGUAGE FlexibleContexts #-}
16+{-# LANGUAGE FlexibleContexts, MultiParamTypeClasses #-}
19−{-# LANGUAGE MultiParamTypeClasses #-}
20
17
21module Language.PureScript.TypeChecker.Types (
18module Language.PureScript.TypeChecker.Types (
22 typesOf
19 typesOf
@@ -36,137 +33,37 @@ module Language.PureScript.TypeChecker.Types (
36
33
37 checkFunctionApplication
34 checkFunctionApplication
38 Check a function of a given type returns a value of another type when applied to its arguments
35 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
42-}
36-}
43
37
38+import Data.Either (lefts, rights)
44import Data.List
39import Data.List
45−import Data.Maybe (maybeToList, fromMaybe)
40+import Data.Maybe (fromMaybe)
46−import Data.Function (on)
47−import Data.Ord (comparing)
48import Data.Monoid
41import 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
50
48
51import Language.PureScript.Declarations
49import Language.PureScript.Declarations
52−import Language.PureScript.Types
50+import Language.PureScript.Environment
51+import Language.PureScript.Errors
53import Language.PureScript.Kinds
52import Language.PureScript.Kinds
54import Language.PureScript.Names
53import Language.PureScript.Names
55−import Language.PureScript.TypeClassDictionaries
54+import Language.PureScript.Pretty
56−import Language.PureScript.TypeChecker.Monad
55+import Language.PureScript.TypeChecker.Entailment
57import Language.PureScript.TypeChecker.Kinds
56import 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
58import Language.PureScript.TypeChecker.Synonyms
61import Language.PureScript.TypeChecker.Synonyms
59−import Language.PureScript.Pretty
62+import Language.PureScript.TypeChecker.Unify
60−import Language.PureScript.Environment
63+import Language.PureScript.TypeClassDictionaries
61−import Language.PureScript.Errors
64+import Language.PureScript.Types
62import qualified Language.PureScript.Constants as C
65import qualified Language.PureScript.Constants as C
63
66
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−
170-- |
67-- |
171-- Infer the types of multiple mutually-recursive values, and return elaborated values including
68-- Infer the types of multiple mutually-recursive values, and return elaborated values including
172-- type class dictionaries and type annotations.
69-- type class dictionaries and type annotations.
@@ -252,7 +149,7 @@ typeForBindingGroupElement (ident, val) dict untypedDict = do
252-- |
149-- |
253-- Check if a value contains a type annotation
150-- Check if a value contains a type annotation
254--
151--
255−isTyped :: (Ident, Expr) -> (Either (Ident, Expr) (Ident, (Expr, Type, Bool)))
152+isTyped :: (Ident, Expr) -> Either (Ident, Expr) (Ident, (Expr, Type, Bool))
256isTyped (name, TypedValue checkType value ty) = Right (name, (value, ty, checkType))
153isTyped (name, TypedValue checkType value ty) = Right (name, (value, ty, checkType))
257isTyped (name, value) = Left (name, value)
154isTyped (name, value) = Left (name, value)
258
155
@@ -281,291 +178,12 @@ replaceTypeClassDictionaries mn =
281 go other = return other
178 go other = return other
282
179
283-- |
180-- |
284−-- A simplified representation of expressions which are used to represent type
181+-- Check the kind of a type, failing if it is not of kind *.
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
559--
182--
560−varIfUnknown :: Type -> Type
183+checkTypeKind :: ModuleName -> Type -> UnifyT t Check ()
561−varIfUnknown ty =
184+checkTypeKind moduleName ty = do
562− let unks = nub $ unknowns ty
185+ kind <- liftCheck $ kindOf moduleName ty
563− toName = (:) 't' . show
186+ guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
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'
569
187
570-- |
188-- |
571-- Remove any ForAlls and ConstrainedType constructors in a type by introducing new unknowns
189-- Remove any ForAlls and ConstrainedType constructors in a type by introducing new unknowns
@@ -584,67 +202,6 @@ instantiatePolyTypeWithUnknowns val (ConstrainedType constraints ty) = do
584 return (foldl App val (map (flip (TypeClassDictionary True) dicts) constraints), ty')
202 return (foldl App val (map (flip (TypeClassDictionary True) dicts) constraints), ty')
585instantiatePolyTypeWithUnknowns val ty = return (val, ty)
203instantiatePolyTypeWithUnknowns val ty = return (val, ty)
586
204
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−
648-- |
205-- |
649-- Infer a type for a value, rethrowing any error to provide a more useful error message
206-- Infer a type for a value, rethrowing any error to provide a more useful error message
650--
207--
@@ -733,8 +290,7 @@ infer' (SuperClassDictionary className tys) = do
733 return $ TypeClassDictionary False (className, tys) dicts
290 return $ TypeClassDictionary False (className, tys) dicts
734infer' (TypedValue checkType val ty) = do
291infer' (TypedValue checkType val ty) = do
735 Just moduleName <- checkCurrentModule <$> get
292 Just moduleName <- checkCurrentModule <$> get
736− kind <- liftCheck $ kindOf moduleName ty
293+ checkTypeKind moduleName ty
737− guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
738 ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
294 ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
739 val' <- if checkType then check val ty' else return val
295 val' <- if checkType then check val ty' else return val
740 return $ TypedValue True val' ty'
296 return $ TypedValue True val' ty'
@@ -745,8 +301,7 @@ inferLetBinding :: [Declaration] -> [Declaration] -> Expr -> (Expr -> UnifyT Typ
745inferLetBinding seen [] ret j = (,) seen <$> makeBindingGroupVisible (j ret)
301inferLetBinding seen [] ret j = (,) seen <$> makeBindingGroupVisible (j ret)
746inferLetBinding seen (ValueDeclaration ident nameKind [] (Right (tv@(TypedValue checkType val ty))) : rest) ret j = do
302inferLetBinding seen (ValueDeclaration ident nameKind [] (Right (tv@(TypedValue checkType val ty))) : rest) ret j = do
747 Just moduleName <- checkCurrentModule <$> get
303 Just moduleName <- checkCurrentModule <$> get
748− kind <- liftCheck $ kindOf moduleName ty
304+ checkTypeKind moduleName ty
749− guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
750 let dict = M.singleton (moduleName, ident) (ty, nameKind, Undefined)
305 let dict = M.singleton (moduleName, ident) (ty, nameKind, Undefined)
751 ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
306 ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
752 TypedValue _ val' ty'' <- if checkType then bindNames dict (check val ty') else return tv
307 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
766 let ds' = [(ident, LocalVariable, val') | (ident, (val', _)) <- ds1' ++ ds2']
321 let ds' = [(ident, LocalVariable, val') | (ident, (val', _)) <- ds1' ++ ds2']
767 makeBindingGroupVisible $ bindNames dict $ inferLetBinding (seen ++ [BindingGroupDeclaration ds']) rest ret j
322 makeBindingGroupVisible $ bindNames dict $ inferLetBinding (seen ++ [BindingGroupDeclaration ds']) rest ret j
768inferLetBinding seen (PositionedDeclaration pos d : ds) ret j = rethrowWithPosition pos $ do
323inferLetBinding 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
770 return (PositionedDeclaration pos d' : ds', val')
325 return (PositionedDeclaration pos d' : ds', val')
771inferLetBinding _ _ _ _ = error "Invalid argument to inferLetBinding"
326inferLetBinding _ _ _ _ = error "Invalid argument to inferLetBinding"
772
327
@@ -865,44 +420,6 @@ checkBinders nvals ret (CaseAlternative binders result : bs) = do
865 rs <- checkBinders nvals ret bs
420 rs <- checkBinders nvals ret bs
866 return $ r : rs
421 return $ r : rs
867
422
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−
906-- |
423-- |
907-- Check the type of a value, rethrowing errors to provide a better error message
424-- Check the type of a value, rethrowing errors to provide a better error message
908--
425--
@@ -986,8 +503,7 @@ check' (SuperClassDictionary className tys) _ = do
986 return $ TypeClassDictionary False (className, tys) dicts
503 return $ TypeClassDictionary False (className, tys) dicts
987check' (TypedValue checkType val ty1) ty2 = do
504check' (TypedValue checkType val ty1) ty2 = do
988 Just moduleName <- checkCurrentModule <$> get
505 Just moduleName <- checkCurrentModule <$> get
989− kind <- liftCheck $ kindOf moduleName ty1
506+ checkTypeKind moduleName ty1
990− guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
991 ty1' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
507 ty1' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
992 ty2' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty2
508 ty2' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty2
993 val' <- subsumes (Just val) ty1' ty2'
509 val' <- subsumes (Just val) ty1' ty2'
@@ -1036,7 +552,7 @@ check' (Constructor c) ty = do
1036 _ <- subsumes Nothing repl ty
552 _ <- subsumes Nothing repl ty
1037 return $ TypedValue True (Constructor c) ty
553 return $ TypedValue True (Constructor c) ty
1038check' (Let ds val) ty = do
554check' (Let ds val) ty = do
1039− (ds', val') <- inferLetBinding [] ds val (flip check ty)
555+ (ds', val') <- inferLetBinding [] ds val (`check` ty)
1040 return $ TypedValue True (Let ds' val') ty
556 return $ TypedValue True (Let ds' val') ty
1041check' val ty | containsTypeSynonyms ty = do
557check' val ty | containsTypeSynonyms ty = do
1042 ty' <- introduceSkolemScope <=< expandAllTypeSynonyms $ ty
558 ty' <- introduceSkolemScope <=< expandAllTypeSynonyms $ ty
@@ -1064,7 +580,7 @@ checkProperties ps row lax = let (ts, r') = rowToList row in go ps ts r' where
1064 go [] [] REmpty = return []
580 go [] [] REmpty = return []
1065 go [] [] u@(TUnknown _) = do u =?= REmpty
581 go [] [] u@(TUnknown _) = do u =?= REmpty
1066 return []
582 return []
1067− go [] [] (Skolem _ _ _) | lax = return []
583+ go [] [] Skolem{} | lax = return []
1068 go [] ((p, _): _) _ | lax = return []
584 go [] ((p, _): _) _ | lax = return []
1069 | otherwise = throwError $ mkErrorStack ("Object does not have property " ++ p) (Just (ExprError (ObjectLiteral ps)))
585 | otherwise = throwError $ mkErrorStack ("Object does not have property " ++ p) (Just (ExprError (ObjectLiteral ps)))
1070 go ((p,_):_) [] REmpty = throwError $ mkErrorStack ("Property " ++ p ++ " is not present in closed object type " ++ prettyPrintRow row) (Just (ExprError (ObjectLiteral ps)))
586 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
1127checkFunctionApplication' fn (SaturatedTypeSynonym name tyArgs) arg ret = do
643checkFunctionApplication' fn (SaturatedTypeSynonym name tyArgs) arg ret = do
1128 ty <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
644 ty <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
1129 checkFunctionApplication fn ty arg ret
645 checkFunctionApplication fn ty arg ret
1130−checkFunctionApplication' fn (KindedType ty _) arg ret = do
646+checkFunctionApplication' fn (KindedType ty _) arg ret =
1131 checkFunctionApplication fn ty arg ret
647 checkFunctionApplication fn ty arg ret
1132checkFunctionApplication' fn (ConstrainedType constraints fnTy) arg ret = do
648checkFunctionApplication' fn (ConstrainedType constraints fnTy) arg ret = do
1133 dicts <- getTypeClassDictionaries
649 dicts <- getTypeClassDictionaries
1134 checkFunctionApplication' (foldl App fn (map (flip (TypeClassDictionary True) dicts) constraints)) fnTy arg ret
650 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{} _ =
1136 return (fnTy, App fn dict)
652 return (fnTy, App fn dict)
1137checkFunctionApplication' _ fnTy arg _ = throwError . strMsg $ "Cannot apply a function of type "
653checkFunctionApplication' _ fnTy arg _ = throwError . strMsg $ "Cannot apply a function of type "
1138 ++ prettyPrintType fnTy
654 ++ prettyPrintType fnTy
1139 ++ " to argument " ++ prettyPrintValue arg
655 ++ " to argument " ++ prettyPrintValue arg
1140
656
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−
1208-- |
657-- |
1209-- Compute the meet of two types, i.e. the most general type which both types subsume.
658-- Compute the meet of two types, i.e. the most general type which both types subsume.
1210-- TODO: handle constrained types
659-- TODO: handle constrained types
@@ -1220,9 +669,8 @@ meet e1 e2 t1 t2 = do
1220 t1 =?= t2
669 t1 =?= t2
1221 return (e1, e2, t1)
670 return (e1, e2, t1)
1222
671
1223−
672+-- |
1224−
673+-- Ensure a set of property names and value does not contain duplicate labels
1225−
674+--
1226−
675+ensureNoDuplicateProperties :: (Error e, MonadError e m) => [(String, Expr)] -> m ()
1227−
676+ensureNoDuplicateProperties ps = guardWith (strMsg "Duplicate property names") $ length (nub . map fst $ ps) == length ps
1228−
src/Language/PureScript/TypeChecker/Unify.hsnew file+172
@@ -0,0 +1,172 @@
1+-----------------------------------------------------------------------------
2+--
3+-- Module : Language.PureScript.TypeChecker.Unify
4+-- Copyright : (c) Phil Freeman 2013
5+-- License : MIT
6+--
7+-- Maintainer : Phil Freeman <paf31@cantab.net>
8+-- Stability : experimental
9+-- Portability :
10+--
11+-- |
12+-- Functions and instances relating to unification
13+--
14+-----------------------------------------------------------------------------
15+
16+{-# OPTIONS_GHC -fno-warn-orphans #-}
17+{-# LANGUAGE FlexibleInstances, FlexibleContexts, MultiParamTypeClasses #-}
18+
19+module Language.PureScript.TypeChecker.Unify (
20+ unifyTypes,
21+ unifyRows,
22+ unifiesWith,
23+ replaceVarWithUnknown,
24+ varIfUnknown
25+) where
26+
27+import Data.List (nub, sort)
28+import Data.Maybe (fromMaybe)
29+import Data.Monoid
30+import qualified Data.HashMap.Strict as H
31+
32+import Control.Monad.Error
33+import Control.Monad.Unify
34+
35+import Language.PureScript.Environment
36+import Language.PureScript.Errors
37+import Language.PureScript.Pretty
38+import Language.PureScript.TypeChecker.Monad
39+import Language.PureScript.TypeChecker.Skolems
40+import Language.PureScript.TypeChecker.Synonyms
41+import Language.PureScript.Types
42+
43+instance Partial Type where
44+ unknown = TUnknown
45+ isUnknown (TUnknown u) = Just u
46+ isUnknown _ = Nothing
47+ unknowns = everythingOnTypes (++) go
48+ where
49+ go (TUnknown u) = [u]
50+ go _ = []
51+ ($?) sub = everywhereOnTypes go
52+ where
53+ go t@(TUnknown u) = fromMaybe t $ H.lookup u (runSubstitution sub)
54+ go other = other
55+
56+instance Unifiable Check Type where
57+ (=?=) = unifyTypes
58+
59+-- |
60+-- Unify two types, updating the current substitution
61+--
62+unifyTypes :: Type -> Type -> UnifyT Type Check ()
63+unifyTypes t1 t2 = rethrow (mkErrorStack ("Error unifying type " ++ prettyPrintType t1 ++ " with type " ++ prettyPrintType t2) Nothing <>) $
64+ unifyTypes' t1 t2
65+ where
66+ unifyTypes' (TUnknown u1) (TUnknown u2) | u1 == u2 = return ()
67+ unifyTypes' (TUnknown u) t = u =:= t
68+ unifyTypes' t (TUnknown u) = u =:= t
69+ unifyTypes' (SaturatedTypeSynonym name args) ty = do
70+ ty1 <- introduceSkolemScope <=< expandTypeSynonym name $ args
71+ ty1 `unifyTypes` ty
72+ unifyTypes' ty s@(SaturatedTypeSynonym _ _) = s `unifyTypes` ty
73+ unifyTypes' (ForAll ident1 ty1 sc1) (ForAll ident2 ty2 sc2) =
74+ case (sc1, sc2) of
75+ (Just sc1', Just sc2') -> do
76+ sko <- newSkolemConstant
77+ let sk1 = skolemize ident1 sko sc1' ty1
78+ let sk2 = skolemize ident2 sko sc2' ty2
79+ sk1 `unifyTypes` sk2
80+ _ -> error "Skolemized type variable was not given a scope"
81+ unifyTypes' (ForAll ident ty1 (Just sc)) ty2 = do
82+ sko <- newSkolemConstant
83+ let sk = skolemize ident sko sc ty1
84+ sk `unifyTypes` ty2
85+ unifyTypes' ForAll{} _ = throwError . strMsg $ "Skolem variable scope is unspecified"
86+ unifyTypes' ty f@ForAll{} = f `unifyTypes` ty
87+ unifyTypes' (TypeVar v1) (TypeVar v2) | v1 == v2 = return ()
88+ unifyTypes' (TypeConstructor c1) (TypeConstructor c2) =
89+ guardWith (strMsg ("Cannot unify " ++ show c1 ++ " with " ++ show c2 ++ ".")) (c1 == c2)
90+ unifyTypes' (TypeApp t3 t4) (TypeApp t5 t6) = do
91+ t3 `unifyTypes` t5
92+ t4 `unifyTypes` t6
93+ unifyTypes' (Skolem _ s1 _) (Skolem _ s2 _) | s1 == s2 = return ()
94+ unifyTypes' (KindedType ty1 _) ty2 = ty1 `unifyTypes` ty2
95+ unifyTypes' ty1 (KindedType ty2 _) = ty1 `unifyTypes` ty2
96+ unifyTypes' r1@RCons{} r2 = unifyRows r1 r2
97+ unifyTypes' r1 r2@RCons{} = unifyRows r1 r2
98+ unifyTypes' r1@REmpty r2 = unifyRows r1 r2
99+ unifyTypes' r1 r2@REmpty = unifyRows r1 r2
100+ unifyTypes' t@(ConstrainedType _ _) _ = throwError . strMsg $ "Attempted to unify a constrained type " ++ prettyPrintType t ++ " with another type."
101+ unifyTypes' t3 t4@(ConstrainedType _ _) = unifyTypes' t4 t3
102+ unifyTypes' t3 t4 = throwError . strMsg $ "Cannot unify " ++ prettyPrintType t3 ++ " with " ++ prettyPrintType t4 ++ "."
103+
104+-- |
105+-- Unify two rows, updating the current substitution
106+--
107+-- Common labels are first identified, and unified. Remaining labels and types are unified with a
108+-- trailing row unification variable, if appropriate, otherwise leftover labels result in a unification
109+-- error.
110+--
111+unifyRows :: Type -> Type -> UnifyT Type Check ()
112+unifyRows r1 r2 =
113+ let
114+ (s1, r1') = rowToList r1
115+ (s2, r2') = rowToList r2
116+ int = [ (t1, t2) | (name, t1) <- s1, (name', t2) <- s2, name == name' ]
117+ sd1 = [ (name, t1) | (name, t1) <- s1, name `notElem` map fst s2 ]
118+ sd2 = [ (name, t2) | (name, t2) <- s2, name `notElem` map fst s1 ]
119+ in do
120+ forM_ int (uncurry (=?=))
121+ unifyRows' sd1 r1' sd2 r2'
122+ where
123+ unifyRows' :: [(String, Type)] -> Type -> [(String, Type)] -> Type -> UnifyT Type Check ()
124+ unifyRows' [] (TUnknown u) sd r = u =:= rowFromList (sd, r)
125+ unifyRows' sd r [] (TUnknown u) = u =:= rowFromList (sd, r)
126+ unifyRows' sd1 (TUnknown u1) sd2 (TUnknown u2) = do
127+ forM_ sd1 $ \(_, t) -> occursCheck u2 t
128+ forM_ sd2 $ \(_, t) -> occursCheck u1 t
129+ rest <- fresh
130+ u1 =:= rowFromList (sd2, rest)
131+ u2 =:= rowFromList (sd1, rest)
132+ unifyRows' [] REmpty [] REmpty = return ()
133+ unifyRows' [] (TypeVar v1) [] (TypeVar v2) | v1 == v2 = return ()
134+ unifyRows' [] (Skolem _ s1 _) [] (Skolem _ s2 _) | s1 == s2 = return ()
135+ unifyRows' sd3 r3 sd4 r4 = throwError . strMsg $ "Cannot unify (" ++ prettyPrintRow (rowFromList (sd3, r3)) ++ ") with (" ++ prettyPrintRow (rowFromList (sd4, r4)) ++ ")"
136+
137+-- |
138+-- Check that two types unify
139+--
140+unifiesWith :: Environment -> Type -> Type -> Bool
141+unifiesWith _ (TUnknown u1) (TUnknown u2) | u1 == u2 = True
142+unifiesWith _ (Skolem _ s1 _) (Skolem _ s2 _) | s1 == s2 = True
143+unifiesWith _ (TypeVar v1) (TypeVar v2) | v1 == v2 = True
144+unifiesWith _ (TypeConstructor c1) (TypeConstructor c2) | c1 == c2 = True
145+unifiesWith e (TypeApp h1 t1) (TypeApp h2 t2) = unifiesWith e h1 h2 && unifiesWith e t1 t2
146+unifiesWith e (SaturatedTypeSynonym name args) t2 =
147+ case expandTypeSynonym' e name args of
148+ Left _ -> False
149+ Right t1 -> unifiesWith e t1 t2
150+unifiesWith e t1 t2@(SaturatedTypeSynonym _ _) = unifiesWith e t2 t1
151+unifiesWith _ _ _ = False
152+
153+-- |
154+-- Replace a single type variable with a new unification variable
155+--
156+replaceVarWithUnknown :: String -> Type -> UnifyT Type Check Type
157+replaceVarWithUnknown ident ty = do
158+ tu <- fresh
159+ return $ replaceTypeVars ident tu ty
160+
161+-- |
162+-- Replace outermost unsolved unification variables with named type variables
163+--
164+varIfUnknown :: Type -> Type
165+varIfUnknown ty =
166+ let unks = nub $ unknowns ty
167+ toName = (:) 't' . show
168+ ty' = everywhereOnTypes typeToVar ty
169+ typeToVar :: Type -> Type
170+ typeToVar (TUnknown u) = TypeVar (toName u)
171+ typeToVar t = t
172+ in mkForAll (sort . map toName $ unks) ty'