git.iko.soy/rowtype-yoga/purescript-native
on fa89354 help sign in
355 lines 17 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, (\\), find, intercalate)
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.AST
41import Language.PureScript.TypeClassDictionaries
42import Language.PureScript.Environment
43import Language.PureScript.Errors
45addDataType :: ModuleName -> DataDeclType -> ProperName -> [(String, Maybe Kind)] -> [(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 (map fst args) dctor tys
53addDataConstructor :: ModuleName -> DataDeclType -> ProperName -> [String] -> ProperName -> [Type] -> Check ()
54addDataConstructor moduleName dtype name args dctor tys = do
55 env <- getEnv
56 mapM_ checkTypeSynonyms tys
57 let retTy = foldl TypeApp (TypeConstructor (Qualified (Just moduleName) name)) (map TypeVar args)
58 let dctorTy = foldr function retTy tys
59 let polyType = mkForAll args dctorTy
60 putEnv $ env { dataConstructors = M.insert (Qualified (Just moduleName) dctor) (dtype, name, polyType) (dataConstructors env) }
62addTypeSynonym :: ModuleName -> ProperName -> [(String, Maybe Kind)] -> Type -> Kind -> Check ()
63addTypeSynonym moduleName name args ty kind = do
64 env <- getEnv
65 checkTypeSynonyms ty
66 putEnv $ env { types = M.insert (Qualified (Just moduleName) name) (kind, TypeSynonym) (types env)
67 , typeSynonyms = M.insert (Qualified (Just moduleName) name) (args, ty) (typeSynonyms env) }
69valueIsNotDefined :: ModuleName -> Ident -> Check ()
70valueIsNotDefined moduleName name = do
71 env <- getEnv
72 case M.lookup (moduleName, name) (names env) of
73 Just _ -> throwError . strMsg $ show name ++ " is already defined"
74 Nothing -> return ()
76addValue :: ModuleName -> Ident -> Type -> NameKind -> Check ()
77addValue moduleName name ty nameKind = do
78 env <- getEnv
79 putEnv (env { names = M.insert (moduleName, name) (ty, nameKind, Defined) (names env) })
81addTypeClass :: ModuleName -> ProperName -> [(String, Maybe Kind)] -> [Constraint] -> [Declaration] -> Check ()
82addTypeClass moduleName pn args implies ds =
83 let members = map toPair ds in
84 modify $ \st -> st { checkEnv = (checkEnv st) { typeClasses = M.insert (Qualified (Just moduleName) pn) (args, members, implies) (typeClasses . checkEnv $ st) } }
85 where
86 toPair (TypeDeclaration ident ty) = (ident, ty)
87 toPair (PositionedDeclaration _ _ d) = toPair d
88 toPair _ = error "Invalid declaration in TypeClassDeclaration"
90addTypeClassDictionaries :: [TypeClassDictionaryInScope] -> Check ()
91addTypeClassDictionaries entries =
92 let mentries = M.fromList [ ((canonicalizeDictionary entry, mn), entry) | entry@TypeClassDictionaryInScope{ tcdName = Qualified mn _ } <- entries ]
93 in modify $ \st -> st { checkEnv = (checkEnv st) { typeClassDictionaries = (typeClassDictionaries . checkEnv $ st) `M.union` mentries } }
95checkDuplicateTypeArguments :: [String] -> Check ()
96checkDuplicateTypeArguments args = for_ firstDup $ \dup ->
97 throwError . strMsg $ "Duplicate type argument '" ++ dup ++ "'"
98 where
99 firstDup :: Maybe String
100 firstDup = listToMaybe $ args \\ nub args
102checkTypeClassInstance :: ModuleName -> Type -> Check ()
103checkTypeClassInstance _ (TypeVar _) = return ()
104checkTypeClassInstance _ (TypeConstructor ctor) = do
105 env <- getEnv
106 when (ctor `M.member` typeSynonyms env) . throwError . strMsg $ "Type synonym instances are disallowed"
107 return ()
108checkTypeClassInstance m (TypeApp t1 t2) = checkTypeClassInstance m t1 >> checkTypeClassInstance m t2
109checkTypeClassInstance _ ty = throwError $ mkErrorStack "Type class instance head is invalid." (Just (TypeError ty))
111-- |
112-- Check that type synonyms are fully-applied in a type
113--
114checkTypeSynonyms :: Type -> Check ()
115checkTypeSynonyms = void . replaceAllTypeSynonyms
117-- |
118-- Type check all declarations in a module
119--
120-- At this point, many declarations will have been desugared, but it is still necessary to
121--
122-- * Kind-check all types and add them to the @Environment@
123--
124-- * Type-check all values and add them to the @Environment@
125--
126-- * Bring type class instances into scope
127--
128-- * Process module imports
129--
130typeCheckAll :: Maybe ModuleName -> ModuleName -> [DeclarationRef] -> [Declaration] -> Check [Declaration]
131typeCheckAll mainModuleName moduleName exps = go
132 where
133 go :: [Declaration] -> Check [Declaration]
134 go [] = return []
135 go (DataDeclaration dtype name args dctors : rest) = do
136 rethrow (strMsg ("Error in type constructor " ++ show name) <>) $ do
137 when (dtype == Newtype) $ checkNewtype dctors
138 checkDuplicateTypeArguments $ map fst args
139 ctorKind <- kindsOf True moduleName name args (concatMap snd dctors)
140 let args' = args `withKinds` ctorKind
141 addDataType moduleName dtype name args' dctors ctorKind
142 ds <- go rest
143 return $ DataDeclaration dtype name args dctors : ds
144 where
145 checkNewtype :: [(ProperName, [Type])] -> Check ()
146 checkNewtype [(_, [_])] = return ()
147 checkNewtype [(_, _)] = throwError . strMsg $ "newtypes constructors must have a single argument"
148 checkNewtype _ = throwError . strMsg $ "newtypes must have a single constructor"
149 go (d@(DataBindingGroupDeclaration tys) : rest) = do
150 rethrow (strMsg "Error in data binding group" <>) $ 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 ds <- go rest
163 return $ d : ds
164 where
165 toTypeSynonym (TypeSynonymDeclaration nm args ty) = Just (nm, args, ty)
166 toTypeSynonym (PositionedDeclaration _ _ d') = toTypeSynonym d'
167 toTypeSynonym _ = Nothing
168 toDataDecl (DataDeclaration dtype nm args dctors) = Just (dtype, nm, args, dctors)
169 toDataDecl (PositionedDeclaration _ _ d') = toDataDecl d'
170 toDataDecl _ = Nothing
171 go (TypeSynonymDeclaration name args ty : rest) = do
172 rethrow (strMsg ("Error in type synonym " ++ show name) <>) $ do
173 checkDuplicateTypeArguments $ map fst args
174 kind <- kindsOf False moduleName name args [ty]
175 let args' = args `withKinds` kind
176 addTypeSynonym moduleName name args' ty kind
177 ds <- go rest
178 return $ TypeSynonymDeclaration name args ty : ds
179 go (TypeDeclaration _ _ : _) = error "Type declarations should have been removed"
180 go (ValueDeclaration name nameKind [] (Right val) : rest) = do
181 d <- rethrow (strMsg ("Error in declaration " ++ show name) <>) $ do
182 valueIsNotDefined moduleName name
183 [(_, (val', ty))] <- typesOf mainModuleName moduleName [(name, val)]
184 addValue moduleName name ty nameKind
185 return $ ValueDeclaration name nameKind [] $ Right val'
186 ds <- go rest
187 return $ d : ds
188 go (ValueDeclaration{} : _) = error "Binders were not desugared"
189 go (BindingGroupDeclaration vals : rest) = do
190 d <- rethrow (strMsg ("Error in binding group " ++ show (map (\(ident, _, _) -> ident) vals)) <>) $ do
191 forM_ (map (\(ident, _, _) -> ident) vals) $ \name ->
192 valueIsNotDefined moduleName name
193 tys <- typesOf mainModuleName moduleName $ map (\(ident, _, ty) -> (ident, ty)) vals
194 vals' <- forM [ (name, val, nameKind, ty)
195 | (name, nameKind, _) <- vals
196 , (name', (val, ty)) <- tys
197 , name == name'
198 ] $ \(name, val, nameKind, ty) -> do
199 addValue moduleName name ty nameKind
200 return (name, nameKind, val)
201 return $ BindingGroupDeclaration vals'
202 ds <- go rest
203 return $ d : ds
204 go (d@(ExternDataDeclaration name kind) : rest) = do
205 env <- getEnv
206 putEnv $ env { types = M.insert (Qualified (Just moduleName) name) (kind, ExternData) (types env) }
207 ds <- go rest
208 return $ d : ds
209 go (d@(ExternDeclaration importTy name _ ty) : rest) = do
210 rethrow (strMsg ("Error in foreign import declaration " ++ show name) <>) $ do
211 env <- getEnv
212 kind <- kindOf moduleName ty
213 guardWith (strMsg "Expected kind *") $ kind == Star
214 case M.lookup (moduleName, name) (names env) of
215 Just _ -> throwError . strMsg $ show name ++ " is already defined"
216 Nothing -> putEnv (env { names = M.insert (moduleName, name) (ty, Extern importTy, Defined) (names env) })
217 ds <- go rest
218 return $ d : ds
219 go (d@(FixityDeclaration _ name) : rest) = do
220 ds <- go rest
221 env <- getEnv
222 guardWith (strMsg ("Fixity declaration with no binding: " ++ name)) $ M.member (moduleName, Op name) $ names env
223 return $ d : ds
224 go (d@(ImportDeclaration importedModule _ _) : rest) = do
225 tcds <- getTypeClassDictionaries
226 let instances = filter (\tcd -> let Qualified (Just mn) _ = tcdName tcd in importedModule == mn) tcds
227 addTypeClassDictionaries [ tcd { tcdName = Qualified (Just moduleName) ident, tcdType = TCDAlias (canonicalizeDictionary tcd) }
228 | tcd <- instances
229 , tcdExported tcd
230 , let (Qualified _ ident) = tcdName tcd
231 ]
232 ds <- go rest
233 return $ d : ds
234 go (d@(TypeClassDeclaration pn args implies tys) : rest) = do
235 addTypeClass moduleName pn args implies tys
236 ds <- go rest
237 return $ d : ds
238 go (d@(TypeInstanceDeclaration dictName deps className tys _) : rest) = do
239 goInstance d dictName deps className tys rest
240 go (d@(ExternInstanceDeclaration dictName deps className tys) : rest) = do
241 goInstance d dictName deps className tys rest
242 go (PositionedDeclaration pos com d : rest) =
243 rethrowWithPosition pos $ do
244 (d' : rest') <- go (d : rest)
245 return (PositionedDeclaration pos com d' : rest')
246 goInstance :: Declaration -> Ident -> [Constraint] -> Qualified ProperName -> [Type] -> [Declaration] -> Check [Declaration]
247 goInstance d dictName deps className tys rest = do
248 mapM_ (checkTypeClassInstance moduleName) tys
249 forM_ deps $ mapM_ (checkTypeClassInstance moduleName) . snd
250 addTypeClassDictionaries [TypeClassDictionaryInScope (Qualified (Just moduleName) dictName) className tys (Just deps) TCDRegular isInstanceExported]
251 ds <- go rest
252 return $ d : ds
254 where
256 isInstanceExported :: Bool
257 isInstanceExported = any exportsInstance exps
259 exportsInstance :: DeclarationRef -> Bool
260 exportsInstance (TypeInstanceRef name) | name == dictName = True
261 exportsInstance (PositionedDeclarationRef _ _ r) = exportsInstance r
262 exportsInstance _ = False
264 -- |
265 -- This function adds the argument kinds for a type constructor so that they may appear in the externs file,
266 -- extracted from the kind of the type constructor itself.
267 --
268 withKinds :: [(String, Maybe Kind)] -> Kind -> [(String, Maybe Kind)]
269 withKinds [] _ = []
270 withKinds (s@(_, Just _ ):ss) (FunKind _ k) = s : withKinds ss k
271 withKinds ( (s, Nothing):ss) (FunKind k1 k2) = (s, Just k1) : withKinds ss k2
272 withKinds _ _ = error "Invalid arguments to peelKinds"
274-- |
275-- Type check an entire module and ensure all types and classes defined within the module that are
276-- required by exported members are also exported.
277--
278typeCheckModule :: Maybe ModuleName -> Module -> Check Module
279typeCheckModule _ (Module _ _ Nothing) = error "exports should have been elaborated"
280typeCheckModule mainModuleName (Module mn decls (Just exps)) = do
281 modify (\s -> s { checkCurrentModule = Just mn })
282 decls' <- typeCheckAll mainModuleName mn exps decls
283 forM_ exps $ \e -> do
284 checkTypesAreExported e
285 checkClassMembersAreExported e
286 checkClassesAreExported e
287 return $ Module mn decls' (Just exps)
288 where
290 checkMemberExport :: (Show a) => String -> (Type -> [a]) -> (a -> Bool) -> DeclarationRef -> Check ()
291 checkMemberExport thing extract test (ValueRef name) = do
292 ty <- lookupVariable mn (Qualified (Just mn) name)
293 case find test (extract ty) of
294 Just hiddenType -> throwError . strMsg $
295 "Error in module '" ++ show mn ++ "':\n\
296 \Exporting declaration '" ++ show name ++ "' requires " ++ thing ++ " '" ++ show hiddenType ++ "' to be exported as well"
297 Nothing -> return ()
298 checkMemberExport _ _ _ _ = return ()
300 -- Check that all the type constructors defined in the current module that appear in member types
301 -- have also been exported from the module
302 checkTypesAreExported :: DeclarationRef -> Check ()
303 checkTypesAreExported = checkMemberExport "type" findTcons isTconHidden
304 where
305 findTcons :: Type -> [ProperName]
306 findTcons = everythingOnTypes (++) go
307 where
308 go (TypeConstructor (Qualified (Just mn') name)) | mn' == mn = [name]
309 go _ = []
310 isTconHidden :: ProperName -> Bool
311 isTconHidden tyName = all go exps
312 where
313 go (TypeRef tyName' _) = tyName' /= tyName
314 go _ = True
316 -- Check that all the classes defined in the current module that appear in member types have also
317 -- been exported from the module
318 checkClassesAreExported :: DeclarationRef -> Check ()
319 checkClassesAreExported = checkMemberExport "class" findClasses isClassHidden
320 where
321 findClasses :: Type -> [ProperName]
322 findClasses = everythingOnTypes (++) go
323 where
324 go (ConstrainedType cs _) = mapMaybe (extractCurrentModuleClass . fst) cs
325 go _ = []
326 extractCurrentModuleClass :: Qualified ProperName -> Maybe ProperName
327 extractCurrentModuleClass (Qualified (Just mn') name) | mn == mn' = Just name
328 extractCurrentModuleClass _ = Nothing
329 isClassHidden :: ProperName -> Bool
330 isClassHidden clsName = all go exps
331 where
332 go (TypeClassRef clsName') = clsName' /= clsName
333 go _ = True
335 checkClassMembersAreExported :: DeclarationRef -> Check ()
336 checkClassMembersAreExported (TypeClassRef name) = do
337 let members = ValueRef `map` head (mapMaybe findClassMembers decls)
338 let missingMembers = members \\ exps
339 unless (null missingMembers) $
340 throwError . strMsg $
341 "Error in module '" ++ show mn ++ "':\n\
342 \Class '" ++ show name ++ "' is exported but is missing member exports for '" ++ intercalate "', '" (map (show . runValueRef) missingMembers) ++ "'"
343 where
344 runValueRef :: DeclarationRef -> Ident
345 runValueRef (ValueRef refName) = refName
346 runValueRef _ = error "non-ValueRef passed to runValueRef"
347 findClassMembers :: Declaration -> Maybe [Ident]
348 findClassMembers (TypeClassDeclaration name' _ _ ds) | name == name' = Just $ map extractMemberName ds
349 findClassMembers (PositionedDeclaration _ _ d) = findClassMembers d
350 findClassMembers _ = Nothing
351 extractMemberName :: Declaration -> Ident
352 extractMemberName (PositionedDeclaration _ _ d) = extractMemberName d
353 extractMemberName (TypeDeclaration memberName _) = memberName
354 extractMemberName _ = error "Unexpected declaration in typeclass member list"
355 checkClassMembersAreExported _ = return ()