git.iko.soy/rowtype-yoga/purescript-native
on 4538687 help sign in
357 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.Except
36import Control.Monad.Error (Error(..))
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 (strMsg ("Error in data constructor " ++ show 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 . strMsg $ show name ++ " is already defined"
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 :: [TypeClassDictionaryInScope] -> Check ()
93addTypeClassDictionaries entries =
94 let mentries = M.fromList [ ((canonicalizeDictionary entry, mn), entry) | entry@TypeClassDictionaryInScope{ tcdName = Qualified mn _ } <- entries ]
95 in modify $ \st -> st { checkEnv = (checkEnv st) { typeClassDictionaries = (typeClassDictionaries . checkEnv $ st) `M.union` mentries } }
97checkDuplicateTypeArguments :: [String] -> Check ()
98checkDuplicateTypeArguments args = for_ firstDup $ \dup ->
99 throwError . strMsg $ "Duplicate type argument '" ++ 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 . strMsg $ "Type synonym instances are disallowed"
109 return ()
110checkTypeClassInstance m (TypeApp t1 t2) = checkTypeClassInstance m t1 >> checkTypeClassInstance m t2
111checkTypeClassInstance _ ty = throwError $ mkErrorStack "Type class instance head is invalid." (Just (TypeError 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 = go
134 where
135 go :: [Declaration] -> Check [Declaration]
136 go [] = return []
137 go (DataDeclaration dtype name args dctors : rest) = do
138 rethrow (strMsg ("Error in type constructor " ++ show name) <>) $ do
139 when (dtype == Newtype) $ checkNewtype dctors
140 checkDuplicateTypeArguments $ map fst args
141 ctorKind <- kindsOf True moduleName name args (concatMap snd dctors)
142 let args' = args `withKinds` ctorKind
143 addDataType moduleName dtype name args' dctors ctorKind
144 ds <- go rest
145 return $ DataDeclaration dtype name args dctors : ds
146 where
147 checkNewtype :: [(ProperName, [Type])] -> Check ()
148 checkNewtype [(_, [_])] = return ()
149 checkNewtype [(_, _)] = throwError . strMsg $ "newtypes constructors must have a single argument"
150 checkNewtype _ = throwError . strMsg $ "newtypes must have a single constructor"
151 go (d@(DataBindingGroupDeclaration tys) : rest) = do
152 rethrow (strMsg "Error in data binding group" <>) $ do
153 let syns = mapMaybe toTypeSynonym tys
154 let dataDecls = mapMaybe toDataDecl tys
155 (syn_ks, data_ks) <- kindsOfAll moduleName syns (map (\(_, name, args, dctors) -> (name, args, concatMap snd dctors)) dataDecls)
156 forM_ (zip dataDecls data_ks) $ \((dtype, name, args, dctors), ctorKind) -> do
157 checkDuplicateTypeArguments $ map fst args
158 let args' = args `withKinds` ctorKind
159 addDataType moduleName dtype name args' dctors ctorKind
160 forM_ (zip syns syn_ks) $ \((name, args, ty), kind) -> do
161 checkDuplicateTypeArguments $ map fst args
162 let args' = args `withKinds` kind
163 addTypeSynonym moduleName name args' ty kind
164 ds <- go rest
165 return $ d : ds
166 where
167 toTypeSynonym (TypeSynonymDeclaration nm args ty) = Just (nm, args, ty)
168 toTypeSynonym (PositionedDeclaration _ _ d') = toTypeSynonym d'
169 toTypeSynonym _ = Nothing
170 toDataDecl (DataDeclaration dtype nm args dctors) = Just (dtype, nm, args, dctors)
171 toDataDecl (PositionedDeclaration _ _ d') = toDataDecl d'
172 toDataDecl _ = Nothing
173 go (TypeSynonymDeclaration name args ty : rest) = do
174 rethrow (strMsg ("Error in type synonym " ++ show name) <>) $ do
175 checkDuplicateTypeArguments $ map fst args
176 kind <- kindsOf False moduleName name args [ty]
177 let args' = args `withKinds` kind
178 addTypeSynonym moduleName name args' ty kind
179 ds <- go rest
180 return $ TypeSynonymDeclaration name args ty : ds
181 go (TypeDeclaration _ _ : _) = error "Type declarations should have been removed"
182 go (ValueDeclaration name nameKind [] (Right val) : rest) = do
183 d <- rethrow (strMsg ("Error in declaration " ++ show name) <>) $ do
184 valueIsNotDefined moduleName name
185 [(_, (val', ty))] <- typesOf mainModuleName moduleName [(name, val)]
186 addValue moduleName name ty nameKind
187 return $ ValueDeclaration name nameKind [] $ Right val'
188 ds <- go rest
189 return $ d : ds
190 go (ValueDeclaration{} : _) = error "Binders were not desugared"
191 go (BindingGroupDeclaration vals : rest) = do
192 d <- rethrow (strMsg ("Error in binding group " ++ show (map (\(ident, _, _) -> ident) vals)) <>) $ do
193 forM_ (map (\(ident, _, _) -> ident) vals) $ \name ->
194 valueIsNotDefined moduleName name
195 tys <- typesOf mainModuleName moduleName $ map (\(ident, _, ty) -> (ident, ty)) vals
196 vals' <- forM [ (name, val, nameKind, ty)
197 | (name, nameKind, _) <- vals
198 , (name', (val, ty)) <- tys
199 , name == name'
200 ] $ \(name, val, nameKind, ty) -> do
201 addValue moduleName name ty nameKind
202 return (name, nameKind, val)
203 return $ BindingGroupDeclaration vals'
204 ds <- go rest
205 return $ d : ds
206 go (d@(ExternDataDeclaration name kind) : rest) = do
207 env <- getEnv
208 putEnv $ env { types = M.insert (Qualified (Just moduleName) name) (kind, ExternData) (types env) }
209 ds <- go rest
210 return $ d : ds
211 go (d@(ExternDeclaration importTy name _ ty) : rest) = do
212 rethrow (strMsg ("Error in foreign import declaration " ++ show name) <>) $ do
213 env <- getEnv
214 kind <- kindOf moduleName ty
215 guardWith (strMsg "Expected kind *") $ kind == Star
216 case M.lookup (moduleName, name) (names env) of
217 Just _ -> throwError . strMsg $ show name ++ " is already defined"
218 Nothing -> putEnv (env { names = M.insert (moduleName, name) (ty, Extern importTy, Defined) (names env) })
219 ds <- go rest
220 return $ d : ds
221 go (d@(FixityDeclaration _ name) : rest) = do
222 ds <- go rest
223 env <- getEnv
224 guardWith (strMsg ("Fixity declaration with no binding: " ++ name)) $ M.member (moduleName, Op name) $ names env
225 return $ d : ds
226 go (d@(ImportDeclaration importedModule _ _) : rest) = do
227 tcds <- getTypeClassDictionaries
228 let instances = filter (\tcd -> let Qualified (Just mn) _ = tcdName tcd in importedModule == mn) tcds
229 addTypeClassDictionaries [ tcd { tcdName = Qualified (Just moduleName) ident, tcdType = TCDAlias (canonicalizeDictionary tcd) }
230 | tcd <- instances
231 , tcdExported tcd
232 , let (Qualified _ ident) = tcdName tcd
233 ]
234 ds <- go rest
235 return $ d : ds
236 go (d@(TypeClassDeclaration pn args implies tys) : rest) = do
237 addTypeClass moduleName pn args implies tys
238 ds <- go rest
239 return $ d : ds
240 go (d@(TypeInstanceDeclaration dictName deps className tys _) : rest) = do
241 goInstance d dictName deps className tys rest
242 go (d@(ExternInstanceDeclaration dictName deps className tys) : rest) = do
243 goInstance d dictName deps className tys rest
244 go (PositionedDeclaration pos com d : rest) =
245 rethrowWithPosition pos $ do
246 (d' : rest') <- go (d : rest)
247 return (PositionedDeclaration pos com d' : rest')
248 goInstance :: Declaration -> Ident -> [Constraint] -> Qualified ProperName -> [Type] -> [Declaration] -> Check [Declaration]
249 goInstance d dictName deps className tys rest = do
250 mapM_ (checkTypeClassInstance moduleName) tys
251 forM_ deps $ mapM_ (checkTypeClassInstance moduleName) . snd
252 addTypeClassDictionaries [TypeClassDictionaryInScope (Qualified (Just moduleName) dictName) className tys (Just deps) TCDRegular isInstanceExported]
253 ds <- go rest
254 return $ d : ds
256 where
258 isInstanceExported :: Bool
259 isInstanceExported = any exportsInstance exps
261 exportsInstance :: DeclarationRef -> Bool
262 exportsInstance (TypeInstanceRef name) | name == dictName = True
263 exportsInstance (PositionedDeclarationRef _ _ r) = exportsInstance r
264 exportsInstance _ = False
266 -- |
267 -- This function adds the argument kinds for a type constructor so that they may appear in the externs file,
268 -- extracted from the kind of the type constructor itself.
269 --
270 withKinds :: [(String, Maybe Kind)] -> Kind -> [(String, Maybe Kind)]
271 withKinds [] _ = []
272 withKinds (s@(_, Just _ ):ss) (FunKind _ k) = s : withKinds ss k
273 withKinds ( (s, Nothing):ss) (FunKind k1 k2) = (s, Just k1) : withKinds ss k2
274 withKinds _ _ = error "Invalid arguments to peelKinds"
276-- |
277-- Type check an entire module and ensure all types and classes defined within the module that are
278-- required by exported members are also exported.
279--
280typeCheckModule :: Maybe ModuleName -> Module -> Check Module
281typeCheckModule _ (Module _ _ Nothing) = error "exports should have been elaborated"
282typeCheckModule mainModuleName (Module mn decls (Just exps)) = do
283 modify (\s -> s { checkCurrentModule = Just mn })
284 decls' <- typeCheckAll mainModuleName mn exps decls
285 forM_ exps $ \e -> do
286 checkTypesAreExported e
287 checkClassMembersAreExported e
288 checkClassesAreExported e
289 return $ Module mn decls' (Just exps)
290 where
292 checkMemberExport :: (Show a) => String -> (Type -> [a]) -> (a -> Bool) -> DeclarationRef -> Check ()
293 checkMemberExport thing extract test (ValueRef name) = do
294 ty <- lookupVariable mn (Qualified (Just mn) name)
295 case find test (extract ty) of
296 Just hiddenType -> throwError . strMsg $
297 "Error in module '" ++ show mn ++ "':\n\
298 \Exporting declaration '" ++ show name ++ "' requires " ++ thing ++ " '" ++ show hiddenType ++ "' to be exported as well"
299 Nothing -> return ()
300 checkMemberExport _ _ _ _ = return ()
302 -- Check that all the type constructors defined in the current module that appear in member types
303 -- have also been exported from the module
304 checkTypesAreExported :: DeclarationRef -> Check ()
305 checkTypesAreExported = checkMemberExport "type" findTcons isTconHidden
306 where
307 findTcons :: Type -> [ProperName]
308 findTcons = everythingOnTypes (++) go
309 where
310 go (TypeConstructor (Qualified (Just mn') name)) | mn' == mn = [name]
311 go _ = []
312 isTconHidden :: ProperName -> Bool
313 isTconHidden tyName = all go exps
314 where
315 go (TypeRef tyName' _) = tyName' /= tyName
316 go _ = True
318 -- Check that all the classes defined in the current module that appear in member types have also
319 -- been exported from the module
320 checkClassesAreExported :: DeclarationRef -> Check ()
321 checkClassesAreExported = checkMemberExport "class" findClasses isClassHidden
322 where
323 findClasses :: Type -> [ProperName]
324 findClasses = everythingOnTypes (++) go
325 where
326 go (ConstrainedType cs _) = mapMaybe (extractCurrentModuleClass . fst) cs
327 go _ = []
328 extractCurrentModuleClass :: Qualified ProperName -> Maybe ProperName
329 extractCurrentModuleClass (Qualified (Just mn') name) | mn == mn' = Just name
330 extractCurrentModuleClass _ = Nothing
331 isClassHidden :: ProperName -> Bool
332 isClassHidden clsName = all go exps
333 where
334 go (TypeClassRef clsName') = clsName' /= clsName
335 go _ = True
337 checkClassMembersAreExported :: DeclarationRef -> Check ()
338 checkClassMembersAreExported (TypeClassRef name) = do
339 let members = ValueRef `map` head (mapMaybe findClassMembers decls)
340 let missingMembers = members \\ exps
341 unless (null missingMembers) $
342 throwError . strMsg $
343 "Error in module '" ++ show mn ++ "':\n\
344 \Class '" ++ show name ++ "' is exported but is missing member exports for '" ++ intercalate "', '" (map (show . runValueRef) missingMembers) ++ "'"
345 where
346 runValueRef :: DeclarationRef -> Ident
347 runValueRef (ValueRef refName) = refName
348 runValueRef _ = error "non-ValueRef passed to runValueRef"
349 findClassMembers :: Declaration -> Maybe [Ident]
350 findClassMembers (TypeClassDeclaration name' _ _ ds) | name == name' = Just $ map extractMemberName ds
351 findClassMembers (PositionedDeclaration _ _ d) = findClassMembers d
352 findClassMembers _ = Nothing
353 extractMemberName :: Declaration -> Ident
354 extractMemberName (PositionedDeclaration _ _ d) = extractMemberName d
355 extractMemberName (TypeDeclaration memberName _) = memberName
356 extractMemberName _ = error "Unexpected declaration in typeclass member list"
357 checkClassMembersAreExported _ = return ()