git.iko.soy/rowtype-yoga/purescript-native
on fd82591 help sign in
334 lines 16 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 typeCheckModule
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.Foldable (for_)
32import qualified Data.Map as M
34import Control.Applicative ((<$>), (<*))
35import Control.Monad.State
36import Control.Monad.Error.Class (MonadError(..))
38import Language.PureScript.Types
39import Language.PureScript.Names
40import Language.PureScript.Kinds
41import Language.PureScript.AST
42import Language.PureScript.TypeClassDictionaries
43import Language.PureScript.Environment
44import Language.PureScript.Errors
46addDataType :: ModuleName -> DataDeclType -> ProperName -> [(String, Maybe Kind)] -> [(ProperName, [Type])] -> Kind -> Check ()
47addDataType moduleName dtype name args dctors ctorKind = do
48 env <- getEnv
49 putEnv $ env { types = M.insert (Qualified (Just moduleName) name) (ctorKind, DataType args dctors) (types env) }
50 forM_ dctors $ \(dctor, tys) ->
51 rethrow (onErrorMessages (ErrorInDataConstructor dctor)) $
52 addDataConstructor moduleName dtype name (map fst args) dctor tys
54addDataConstructor :: ModuleName -> DataDeclType -> ProperName -> [String] -> ProperName -> [Type] -> Check ()
55addDataConstructor moduleName dtype name args dctor tys = do
56 env <- getEnv
57 mapM_ checkTypeSynonyms tys
58 let retTy = foldl TypeApp (TypeConstructor (Qualified (Just moduleName) name)) (map TypeVar args)
59 let dctorTy = foldr function retTy tys
60 let polyType = mkForAll args dctorTy
61 let fields = [Ident ("value" ++ show n) | n <- [0..(length tys - 1)]]
62 putEnv $ env { dataConstructors = M.insert (Qualified (Just moduleName) dctor) (dtype, name, polyType, fields) (dataConstructors env) }
64addTypeSynonym :: ModuleName -> ProperName -> [(String, Maybe Kind)] -> Type -> Kind -> Check ()
65addTypeSynonym moduleName name args ty kind = do
66 env <- getEnv
67 checkTypeSynonyms ty
68 putEnv $ env { types = M.insert (Qualified (Just moduleName) name) (kind, TypeSynonym) (types env)
69 , typeSynonyms = M.insert (Qualified (Just moduleName) name) (args, ty) (typeSynonyms env) }
71valueIsNotDefined :: ModuleName -> Ident -> Check ()
72valueIsNotDefined moduleName name = do
73 env <- getEnv
74 case M.lookup (moduleName, name) (names env) of
75 Just _ -> throwError . errorMessage $ RedefinedIdent name
76 Nothing -> return ()
78addValue :: ModuleName -> Ident -> Type -> NameKind -> Check ()
79addValue moduleName name ty nameKind = do
80 env <- getEnv
81 putEnv (env { names = M.insert (moduleName, name) (ty, nameKind, Defined) (names env) })
83addTypeClass :: ModuleName -> ProperName -> [(String, Maybe Kind)] -> [Constraint] -> [Declaration] -> Check ()
84addTypeClass moduleName pn args implies ds =
85 let members = map toPair ds in
86 modify $ \st -> st { checkEnv = (checkEnv st) { typeClasses = M.insert (Qualified (Just moduleName) pn) (args, members, implies) (typeClasses . checkEnv $ st) } }
87 where
88 toPair (TypeDeclaration ident ty) = (ident, ty)
89 toPair (PositionedDeclaration _ _ d) = toPair d
90 toPair _ = error "Invalid declaration in TypeClassDeclaration"
92addTypeClassDictionaries :: Maybe ModuleName -> M.Map (Qualified ProperName) (M.Map (Qualified Ident) TypeClassDictionaryInScope) -> Check ()
93addTypeClassDictionaries mn entries =
94 modify $ \st -> st { checkEnv = (checkEnv st) { typeClassDictionaries = insertState st } }
95 where insertState st = M.insertWith (M.unionWith M.union) mn entries (typeClassDictionaries . checkEnv $ st)
97checkDuplicateTypeArguments :: [String] -> Check ()
98checkDuplicateTypeArguments args = for_ firstDup $ \dup ->
99 throwError . errorMessage $ DuplicateTypeArgument dup
100 where
101 firstDup :: Maybe String
102 firstDup = listToMaybe $ args \\ nub args
104checkTypeClassInstance :: ModuleName -> Type -> Check ()
105checkTypeClassInstance _ (TypeVar _) = return ()
106checkTypeClassInstance _ (TypeConstructor ctor) = do
107 env <- getEnv
108 when (ctor `M.member` typeSynonyms env) . throwError . errorMessage $ TypeSynonymInstance
109 return ()
110checkTypeClassInstance m (TypeApp t1 t2) = checkTypeClassInstance m t1 >> checkTypeClassInstance m t2
111checkTypeClassInstance _ ty = throwError . errorMessage $ InvalidInstanceHead ty
113-- |
114-- Check that type synonyms are fully-applied in a type
115--
116checkTypeSynonyms :: Type -> Check ()
117checkTypeSynonyms = void . replaceAllTypeSynonyms
119-- |
120-- Type check all declarations in a module
121--
122-- At this point, many declarations will have been desugared, but it is still necessary to
123--
124-- * Kind-check all types and add them to the @Environment@
125--
126-- * Type-check all values and add them to the @Environment@
127--
128-- * Bring type class instances into scope
129--
130-- * Process module imports
131--
132typeCheckAll :: Maybe ModuleName -> ModuleName -> [DeclarationRef] -> [Declaration] -> Check [Declaration]
133typeCheckAll mainModuleName moduleName exps ds = mapM go ds <* mapM_ checkOrphanFixities ds
134 where
135 go :: Declaration -> Check Declaration
136 go (DataDeclaration dtype name args dctors) = do
137 rethrow (onErrorMessages (ErrorInTypeConstructor name)) $ do
138 when (dtype == Newtype) $ checkNewtype dctors
139 checkDuplicateTypeArguments $ map fst args
140 ctorKind <- kindsOf True moduleName name args (concatMap snd dctors)
141 let args' = args `withKinds` ctorKind
142 addDataType moduleName dtype name args' dctors ctorKind
143 return $ DataDeclaration dtype name args dctors
144 where
145 checkNewtype :: [(ProperName, [Type])] -> Check ()
146 checkNewtype [(_, [_])] = return ()
147 checkNewtype [(_, _)] = throwError . errorMessage $ InvalidNewtype
148 checkNewtype _ = throwError . errorMessage $ InvalidNewtype
149 go (d@(DataBindingGroupDeclaration tys)) = do
150 rethrow (onErrorMessages ErrorInDataBindingGroup) $ do
151 let syns = mapMaybe toTypeSynonym tys
152 let dataDecls = mapMaybe toDataDecl tys
153 (syn_ks, data_ks) <- kindsOfAll moduleName syns (map (\(_, name, args, dctors) -> (name, args, concatMap snd dctors)) dataDecls)
154 forM_ (zip dataDecls data_ks) $ \((dtype, name, args, dctors), ctorKind) -> do
155 checkDuplicateTypeArguments $ map fst args
156 let args' = args `withKinds` ctorKind
157 addDataType moduleName dtype name args' dctors ctorKind
158 forM_ (zip syns syn_ks) $ \((name, args, ty), kind) -> do
159 checkDuplicateTypeArguments $ map fst args
160 let args' = args `withKinds` kind
161 addTypeSynonym moduleName name args' ty kind
162 return d
163 where
164 toTypeSynonym (TypeSynonymDeclaration nm args ty) = Just (nm, args, ty)
165 toTypeSynonym (PositionedDeclaration _ _ d') = toTypeSynonym d'
166 toTypeSynonym _ = Nothing
167 toDataDecl (DataDeclaration dtype nm args dctors) = Just (dtype, nm, args, dctors)
168 toDataDecl (PositionedDeclaration _ _ d') = toDataDecl d'
169 toDataDecl _ = Nothing
170 go (TypeSynonymDeclaration name args ty) = do
171 rethrow (onErrorMessages (ErrorInTypeSynonym name)) $ do
172 checkDuplicateTypeArguments $ map fst args
173 kind <- kindsOf False moduleName name args [ty]
174 let args' = args `withKinds` kind
175 addTypeSynonym moduleName name args' ty kind
176 return $ TypeSynonymDeclaration name args ty
177 go (TypeDeclaration{}) = error "Type declarations should have been removed"
178 go (ValueDeclaration name nameKind [] (Right val)) =
179 rethrow (onErrorMessages (ErrorInValueDeclaration name)) $ do
180 valueIsNotDefined moduleName name
181 [(_, (val', ty))] <- typesOf mainModuleName moduleName [(name, val)]
182 addValue moduleName name ty nameKind
183 return $ ValueDeclaration name nameKind [] $ Right val'
184 go (ValueDeclaration{}) = error "Binders were not desugared"
185 go (BindingGroupDeclaration vals) =
186 rethrow (onErrorMessages (ErrorInBindingGroup (map (\(ident, _, _) -> ident) vals))) $ do
187 forM_ (map (\(ident, _, _) -> ident) vals) $ \name ->
188 valueIsNotDefined moduleName name
189 tys <- typesOf mainModuleName moduleName $ map (\(ident, _, ty) -> (ident, ty)) vals
190 vals' <- forM [ (name, val, nameKind, ty)
191 | (name, nameKind, _) <- vals
192 , (name', (val, ty)) <- tys
193 , name == name'
194 ] $ \(name, val, nameKind, ty) -> do
195 addValue moduleName name ty nameKind
196 return (name, nameKind, val)
197 return $ BindingGroupDeclaration vals'
198 go (d@(ExternDataDeclaration name kind)) = do
199 env <- getEnv
200 putEnv $ env { types = M.insert (Qualified (Just moduleName) name) (kind, ExternData) (types env) }
201 return d
202 go (d@(ExternDeclaration name ty)) = do
203 rethrow (onErrorMessages (ErrorInForeignImport name)) $ do
204 env <- getEnv
205 kind <- kindOf moduleName ty
206 guardWith (errorMessage (ExpectedType kind)) $ kind == Star
207 case M.lookup (moduleName, name) (names env) of
208 Just _ -> throwError . errorMessage $ RedefinedIdent name
209 Nothing -> putEnv (env { names = M.insert (moduleName, name) (ty, External, Defined) (names env) })
210 return d
211 go (d@(FixityDeclaration{})) = return d
212 go (d@(ImportDeclaration importedModule _ _)) = do
213 instances <- lookupTypeClassDictionaries $ Just importedModule
214 addTypeClassDictionaries (Just moduleName) instances
215 return d
216 go (d@(TypeClassDeclaration pn args implies tys)) = do
217 addTypeClass moduleName pn args implies tys
218 return d
219 go (d@(TypeInstanceDeclaration dictName deps className tys _)) =
220 goInstance d dictName deps className tys
221 go (d@(ExternInstanceDeclaration dictName deps className tys)) =
222 goInstance d dictName deps className tys
223 go (PositionedDeclaration pos com d) =
224 rethrowWithPosition pos $ PositionedDeclaration pos com <$> go d
226 checkOrphanFixities :: Declaration -> Check ()
227 checkOrphanFixities (FixityDeclaration _ name) = do
228 env <- getEnv
229 guardWith (errorMessage (OrphanFixityDeclaration name)) $ M.member (moduleName, Op name) $ names env
230 checkOrphanFixities (PositionedDeclaration pos _ d) =
231 rethrowWithPosition pos $ checkOrphanFixities d
232 checkOrphanFixities _ = return ()
234 goInstance :: Declaration -> Ident -> [Constraint] -> Qualified ProperName -> [Type] -> Check Declaration
235 goInstance d dictName deps className tys = do
236 mapM_ (checkTypeClassInstance moduleName) tys
237 forM_ deps $ mapM_ (checkTypeClassInstance moduleName) . snd
238 let dict = TypeClassDictionaryInScope (Qualified (Just moduleName) dictName) className tys (Just deps) TCDRegular isInstanceExported
239 addTypeClassDictionaries (Just moduleName) . M.singleton className $ M.singleton (canonicalizeDictionary dict) dict
240 return d
242 where
244 isInstanceExported :: Bool
245 isInstanceExported = any exportsInstance exps
247 exportsInstance :: DeclarationRef -> Bool
248 exportsInstance (TypeInstanceRef name) | name == dictName = True
249 exportsInstance (PositionedDeclarationRef _ _ r) = exportsInstance r
250 exportsInstance _ = False
252 -- |
253 -- This function adds the argument kinds for a type constructor so that they may appear in the externs file,
254 -- extracted from the kind of the type constructor itself.
255 --
256 withKinds :: [(String, Maybe Kind)] -> Kind -> [(String, Maybe Kind)]
257 withKinds [] _ = []
258 withKinds (s@(_, Just _ ):ss) (FunKind _ k) = s : withKinds ss k
259 withKinds ( (s, Nothing):ss) (FunKind k1 k2) = (s, Just k1) : withKinds ss k2
260 withKinds _ _ = error "Invalid arguments to peelKinds"
262-- |
263-- Type check an entire module and ensure all types and classes defined within the module that are
264-- required by exported members are also exported.
265--
266typeCheckModule :: Maybe ModuleName -> Module -> Check Module
267typeCheckModule _ (Module _ _ _ Nothing) = error "exports should have been elaborated"
268typeCheckModule mainModuleName (Module coms mn decls (Just exps)) = rethrow (onErrorMessages (ErrorInModule mn)) $ do
269 modify (\s -> s { checkCurrentModule = Just mn })
270 decls' <- typeCheckAll mainModuleName mn exps decls
271 forM_ exps $ \e -> do
272 checkTypesAreExported e
273 checkClassMembersAreExported e
274 checkClassesAreExported e
275 return $ Module coms mn decls' (Just exps)
276 where
278 checkMemberExport :: (Type -> [DeclarationRef]) -> DeclarationRef -> Check ()
279 checkMemberExport extract dr@(ValueRef name) = do
280 ty <- lookupVariable mn (Qualified (Just mn) name)
281 case filter (not . exported) (extract ty) of
282 [] -> return ()
283 hidden -> throwError . errorMessage $ TransitiveExportError dr hidden
284 where
285 exported e = any (exports e) exps
286 exports (TypeRef pn1 _) (TypeRef pn2 _) = pn1 == pn2
287 exports (ValueRef id1) (ValueRef id2) = id1 == id2
288 exports (TypeClassRef pn1) (TypeClassRef pn2) = pn1 == pn2
289 exports (TypeInstanceRef id1) (TypeInstanceRef id2) = id1 == id2
290 exports (PositionedDeclarationRef _ _ r1) r2 = exports r1 r2
291 exports r1 (PositionedDeclarationRef _ _ r2) = exports r1 r2
292 exports _ _ = False
293 checkMemberExport _ _ = return ()
295 -- Check that all the type constructors defined in the current module that appear in member types
296 -- have also been exported from the module
297 checkTypesAreExported :: DeclarationRef -> Check ()
298 checkTypesAreExported = checkMemberExport findTcons
299 where
300 findTcons :: Type -> [DeclarationRef]
301 findTcons = everythingOnTypes (++) go
302 where
303 go (TypeConstructor (Qualified (Just mn') name)) | mn' == mn = [TypeRef name (error "Data constructors unused in checkTypesAreExported")]
304 go _ = []
306 -- Check that all the classes defined in the current module that appear in member types have also
307 -- been exported from the module
308 checkClassesAreExported :: DeclarationRef -> Check ()
309 checkClassesAreExported = checkMemberExport findClasses
310 where
311 findClasses :: Type -> [DeclarationRef]
312 findClasses = everythingOnTypes (++) go
313 where
314 go (ConstrainedType cs _) = mapMaybe (fmap TypeClassRef . extractCurrentModuleClass . fst) cs
315 go _ = []
316 extractCurrentModuleClass :: Qualified ProperName -> Maybe ProperName
317 extractCurrentModuleClass (Qualified (Just mn') name) | mn == mn' = Just name
318 extractCurrentModuleClass _ = Nothing
320 checkClassMembersAreExported :: DeclarationRef -> Check ()
321 checkClassMembersAreExported dr@(TypeClassRef name) = do
322 let members = ValueRef `map` head (mapMaybe findClassMembers decls)
323 let missingMembers = members \\ exps
324 unless (null missingMembers) $ throwError . errorMessage $ TransitiveExportError dr members
325 where
326 findClassMembers :: Declaration -> Maybe [Ident]
327 findClassMembers (TypeClassDeclaration name' _ _ ds) | name == name' = Just $ map extractMemberName ds
328 findClassMembers (PositionedDeclaration _ _ d) = findClassMembers d
329 findClassMembers _ = Nothing
330 extractMemberName :: Declaration -> Ident
331 extractMemberName (PositionedDeclaration _ _ d) = extractMemberName d
332 extractMemberName (TypeDeclaration memberName _) = memberName
333 extractMemberName _ = error "Unexpected declaration in typeclass member list"
334 checkClassMembersAreExported _ = return ()