git.iko.soy/rowtype-yoga/purescript-native
on 73a023f help sign in
246 lines 11 kB history raw
1-----------------------------------------------------------------------------
2--
3-- Module : Language.PureScript.TypeChecker
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-- The top-level type checker, which checks all declarations in a module.
13--
14-----------------------------------------------------------------------------
16{-# LANGUAGE FlexibleInstances #-}
18module Language.PureScript.TypeChecker (
19 module T,
20 typeCheckAll
21) where
23import Language.PureScript.TypeChecker.Monad as T
24import Language.PureScript.TypeChecker.Kinds as T
25import Language.PureScript.TypeChecker.Types as T
26import Language.PureScript.TypeChecker.Synonyms as T
28import Data.Maybe
29import Data.List (nub, (\\))
30import Data.Monoid ((<>))
31import Data.Foldable (for_)
32import qualified Data.Map as M
34import Control.Monad.State
35import Control.Monad.Error
37import Language.PureScript.Types
38import Language.PureScript.Names
39import Language.PureScript.Kinds
40import Language.PureScript.Declarations
41import Language.PureScript.TypeClassDictionaries
42import Language.PureScript.Environment
43import Language.PureScript.Errors
45addDataType :: ModuleName -> DataDeclType -> ProperName -> [String] -> [(ProperName, [Type])] -> Kind -> Check ()
46addDataType moduleName dtype name args dctors ctorKind = do
47 env <- getEnv
48 putEnv $ env { types = M.insert (Qualified (Just moduleName) name) (ctorKind, DataType args dctors) (types env) }
49 forM_ dctors $ \(dctor, tys) ->
50 rethrow (strMsg ("Error in data constructor " ++ show dctor) <>) $
51 addDataConstructor moduleName dtype name args dctor tys
53addDataConstructor :: ModuleName -> DataDeclType -> ProperName -> [String] -> ProperName -> [Type] -> Check ()
54addDataConstructor moduleName dtype name args dctor tys = do
55 env <- getEnv
56 let retTy = foldl TypeApp (TypeConstructor (Qualified (Just moduleName) name)) (map TypeVar args)
57 let dctorTy = foldr function retTy tys
58 let polyType = mkForAll args dctorTy
59 putEnv $ env { dataConstructors = M.insert (Qualified (Just moduleName) dctor) (dtype, name, polyType) (dataConstructors env) }
61addTypeSynonym :: ModuleName -> ProperName -> [String] -> Type -> Kind -> Check ()
62addTypeSynonym moduleName name args ty kind = do
63 env <- getEnv
64 putEnv $ env { types = M.insert (Qualified (Just moduleName) name) (kind, TypeSynonym) (types env)
65 , typeSynonyms = M.insert (Qualified (Just moduleName) name) (args, ty) (typeSynonyms env) }
67valueIsNotDefined :: ModuleName -> Ident -> Check ()
68valueIsNotDefined moduleName name = do
69 env <- getEnv
70 case M.lookup (moduleName, name) (names env) of
71 Just _ -> throwError . strMsg $ show name ++ " is already defined"
72 Nothing -> return ()
74addValue :: ModuleName -> Ident -> Type -> NameKind -> Check ()
75addValue moduleName name ty nameKind = do
76 env <- getEnv
77 putEnv (env { names = M.insert (moduleName, name) (ty, nameKind, Defined) (names env) })
79addTypeClass :: ModuleName -> ProperName -> [String] -> [(Qualified ProperName, [Type])] -> [Declaration] -> Check ()
80addTypeClass moduleName pn args implies ds =
81 let members = map toPair ds in
82 modify $ \st -> st { checkEnv = (checkEnv st) { typeClasses = M.insert (Qualified (Just moduleName) pn) (args, members, implies) (typeClasses . checkEnv $ st) } }
83 where
84 toPair (TypeDeclaration ident ty) = (ident, ty)
85 toPair (PositionedDeclaration _ d) = toPair d
86 toPair _ = error "Invalid declaration in TypeClassDeclaration"
88addTypeClassDictionaries :: [TypeClassDictionaryInScope] -> Check ()
89addTypeClassDictionaries entries =
90 let mentries = M.fromList [ ((canonicalizeDictionary entry, mn), entry) | entry@TypeClassDictionaryInScope{ tcdName = Qualified mn _ } <- entries ]
91 in modify $ \st -> st { checkEnv = (checkEnv st) { typeClassDictionaries = (typeClassDictionaries . checkEnv $ st) `M.union` mentries } }
93checkDuplicateTypeArguments :: [String] -> Check ()
94checkDuplicateTypeArguments args = for_ firstDup $ \dup ->
95 throwError . strMsg $ "Duplicate type argument '" ++ dup ++ "'"
96 where
97 firstDup :: Maybe String
98 firstDup = listToMaybe $ args \\ nub args
100checkTypeClassInstance :: ModuleName -> Type -> Check ()
101checkTypeClassInstance _ (TypeVar _) = return ()
102checkTypeClassInstance _ (TypeConstructor ctor) = do
103 env <- getEnv
104 when (ctor `M.member` typeSynonyms env) . throwError . strMsg $ "Type synonym instances are disallowed"
105 return ()
106checkTypeClassInstance m (TypeApp t1 t2) = checkTypeClassInstance m t1 >> checkTypeClassInstance m t2
107checkTypeClassInstance _ ty = throwError $ mkErrorStack "Type class instance head is invalid." (Just (TypeError ty))
109-- |
110-- Type check all declarations in a module
111--
112-- At this point, many declarations will have been desugared, but it is still necessary to
113--
114-- * Kind-check all types and add them to the @Environment@
115--
116-- * Type-check all values and add them to the @Environment@
117--
118-- * Bring type class instances into scope
119--
120-- * Process module imports
121--
122typeCheckAll :: Maybe ModuleName -> ModuleName -> Maybe [DeclarationRef] -> [Declaration] -> Check [Declaration]
123typeCheckAll mainModuleName moduleName exps = go
124 where
125 go :: [Declaration] -> Check [Declaration]
126 go [] = return []
127 go (d@(DataDeclaration dtype name args dctors) : rest) = do
128 rethrow (strMsg ("Error in type constructor " ++ show name) <>) $ do
129 when (dtype == Newtype) $ checkNewtype dctors
130 checkDuplicateTypeArguments args
131 ctorKind <- kindsOf True moduleName name args (concatMap snd dctors)
132 addDataType moduleName dtype name args dctors ctorKind
133 ds <- go rest
134 return $ d : ds
135 where
136 checkNewtype :: [(ProperName, [Type])] -> Check ()
137 checkNewtype [(_, [_])] = return ()
138 checkNewtype [(_, _)] = throwError . strMsg $ "newtypes constructors must have a single argument"
139 checkNewtype _ = throwError . strMsg $ "newtypes must have a single constructor"
140 go (d@(DataBindingGroupDeclaration tys) : rest) = do
141 rethrow (strMsg "Error in data binding group" <>) $ do
142 let syns = mapMaybe toTypeSynonym tys
143 let dataDecls = mapMaybe toDataDecl tys
144 (syn_ks, data_ks) <- kindsOfAll moduleName syns (map (\(_, name, args, dctors) -> (name, args, concatMap snd dctors)) dataDecls)
145 forM_ (zip dataDecls data_ks) $ \((dtype, name, args, dctors), ctorKind) -> do
146 checkDuplicateTypeArguments args
147 addDataType moduleName dtype name args dctors ctorKind
148 forM_ (zip syns syn_ks) $ \((name, args, ty), kind) -> do
149 checkDuplicateTypeArguments args
150 addTypeSynonym moduleName name args ty kind
151 ds <- go rest
152 return $ d : ds
153 where
154 toTypeSynonym (TypeSynonymDeclaration nm args ty) = Just (nm, args, ty)
155 toTypeSynonym (PositionedDeclaration _ d') = toTypeSynonym d'
156 toTypeSynonym _ = Nothing
157 toDataDecl (DataDeclaration dtype nm args dctors) = Just (dtype, nm, args, dctors)
158 toDataDecl (PositionedDeclaration _ d') = toDataDecl d'
159 toDataDecl _ = Nothing
160 go (d@(TypeSynonymDeclaration name args ty) : rest) = do
161 rethrow (strMsg ("Error in type synonym " ++ show name) <>) $ do
162 checkDuplicateTypeArguments args
163 kind <- kindsOf False moduleName name args [ty]
164 addTypeSynonym moduleName name args ty kind
165 ds <- go rest
166 return $ d : ds
167 go (TypeDeclaration _ _ : _) = error "Type declarations should have been removed"
168 go (ValueDeclaration name nameKind [] Nothing val : rest) = do
169 d <- rethrow (strMsg ("Error in declaration " ++ show name) <>) $ do
170 valueIsNotDefined moduleName name
171 [(_, (val', ty))] <- typesOf mainModuleName moduleName [(name, val)]
172 addValue moduleName name ty nameKind
173 return $ ValueDeclaration name nameKind [] Nothing val'
174 ds <- go rest
175 return $ d : ds
176 go (ValueDeclaration{} : _) = error "Binders were not desugared"
177 go (BindingGroupDeclaration vals : rest) = do
178 d <- rethrow (strMsg ("Error in binding group " ++ show (map (\(ident, _, _) -> ident) vals)) <>) $ do
179 forM_ (map (\(ident, _, _) -> ident) vals) $ \name ->
180 valueIsNotDefined moduleName name
181 tys <- typesOf mainModuleName moduleName $ map (\(ident, _, ty) -> (ident, ty)) vals
182 vals' <- forM (zipWith (\(name, nameKind, _) (_, (val, ty)) -> (name, val, nameKind, ty)) vals tys) $ \(name, val, nameKind, ty) -> do
183 addValue moduleName name ty nameKind
184 return (name, nameKind, val)
185 return $ BindingGroupDeclaration vals'
186 ds <- go rest
187 return $ d : ds
188 go (d@(ExternDataDeclaration name kind) : rest) = do
189 env <- getEnv
190 putEnv $ env { types = M.insert (Qualified (Just moduleName) name) (kind, ExternData) (types env) }
191 ds <- go rest
192 return $ d : ds
193 go (d@(ExternDeclaration importTy name _ ty) : rest) = do
194 rethrow (strMsg ("Error in foreign import declaration " ++ show name) <>) $ do
195 env <- getEnv
196 kind <- kindOf moduleName ty
197 guardWith (strMsg "Expected kind *") $ kind == Star
198 case M.lookup (moduleName, name) (names env) of
199 Just _ -> throwError . strMsg $ show name ++ " is already defined"
200 Nothing -> putEnv (env { names = M.insert (moduleName, name) (ty, Extern importTy, Defined) (names env) })
201 ds <- go rest
202 return $ d : ds
203 go (d@(FixityDeclaration _ name) : rest) = do
204 ds <- go rest
205 env <- getEnv
206 guardWith (strMsg ("Fixity declaration with no binding: " ++ name)) $ M.member (moduleName, Op name) $ names env
207 return $ d : ds
208 go (d@(ImportDeclaration importedModule _ _) : rest) = do
209 tcds <- getTypeClassDictionaries
210 let instances = filter (\tcd -> let Qualified (Just mn) _ = tcdName tcd in importedModule == mn) tcds
211 addTypeClassDictionaries [ tcd { tcdName = Qualified (Just moduleName) ident, tcdType = TCDAlias (canonicalizeDictionary tcd) }
212 | tcd <- instances
213 , tcdExported tcd
214 , let (Qualified _ ident) = tcdName tcd
215 ]
216 ds <- go rest
217 return $ d : ds
218 go (d@(TypeClassDeclaration pn args implies tys) : rest) = do
219 addTypeClass moduleName pn args implies tys
220 ds <- go rest
221 return $ d : ds
222 go (TypeInstanceDeclaration dictName deps className tys _ : rest) = do
223 go (ExternInstanceDeclaration dictName deps className tys : rest)
224 go (d@(ExternInstanceDeclaration dictName deps className tys) : rest) = do
225 mapM_ (checkTypeClassInstance moduleName) tys
226 forM_ deps $ mapM_ (checkTypeClassInstance moduleName) . snd
227 addTypeClassDictionaries [TypeClassDictionaryInScope (Qualified (Just moduleName) dictName) className tys (Just deps) TCDRegular isInstanceExported]
228 ds <- go rest
229 return $ d : ds
230 where
231 isInstanceExported :: Bool
232 isInstanceExported = maybe True (any exportsInstance) exps
234 exportsInstance :: DeclarationRef -> Bool
235 exportsInstance (TypeInstanceRef name) | name == dictName = True
236 exportsInstance (PositionedDeclarationRef _ r) = exportsInstance r
237 exportsInstance _ = False
239 go (PositionedDeclaration pos d : rest) =
240 rethrowWithPosition pos $ do
241 (d' : rest') <- go (d : rest)
242 return (PositionedDeclaration pos d' : rest')