1{-# LANGUAGE FlexibleInstances #-}
4-- The top-level type checker, which checks all declarations in a module.
6module Language.PureScript.TypeChecker
13import Control.Monad (when, unless, void, forM, forM_)
14import Control.Monad.Error.Class (MonadError(..))
15import Control.Monad.State.Class (MonadState(..), modify)
16import Control.Monad.Supply.Class (MonadSupply)
17import Control.Monad.Writer.Class (MonadWriter(..))
19import Data.Foldable (for_, traverse_)
20import Data.List (nub, nubBy, (\\), sort, group)
22import qualified Data.Map as M
24import Language.PureScript.AST
25import Language.PureScript.Crash
26import Language.PureScript.Environment
27import Language.PureScript.Errors
28import Language.PureScript.Kinds
29import Language.PureScript.Linter
30import Language.PureScript.Names
31import Language.PureScript.Traversals
32import Language.PureScript.TypeChecker.Kinds as T
33import Language.PureScript.TypeChecker.Monad as T
34import Language.PureScript.TypeChecker.Synonyms as T
35import Language.PureScript.TypeChecker.Types as T
36import Language.PureScript.TypeClassDictionaries
37import Language.PureScript.Types
40 :: (MonadState CheckState m, MonadError MultipleErrors m, MonadWriter MultipleErrors m)
43 -> ProperName 'TypeName
44 -> [(String, Maybe Kind)]
45 -> [(ProperName 'ConstructorName, [Type])]
48addDataType moduleName dtype name args dctors ctorKind = do
50 putEnv $ env { types = M.insert (Qualified (Just moduleName) name) (ctorKind, DataType args dctors) (types env) }
51 for_ dctors $ \(dctor, tys) ->
52 warnAndRethrow (addHint (ErrorInDataConstructor dctor)) $
53 addDataConstructor moduleName dtype name (map fst args) dctor tys
56 :: (MonadState CheckState m, MonadError MultipleErrors m)
59 -> ProperName 'TypeName
61 -> ProperName 'ConstructorName
64addDataConstructor moduleName dtype name args dctor tys = do
66 traverse_ checkTypeSynonyms tys
67 let retTy = foldl TypeApp (TypeConstructor (Qualified (Just moduleName) name)) (map TypeVar args)
68 let dctorTy = foldr function retTy tys
69 let polyType = mkForAll args dctorTy
70 let fields = [Ident ("value" ++ show n) | n <- [0..(length tys - 1)]]
71 putEnv $ env { dataConstructors = M.insert (Qualified (Just moduleName) dctor) (dtype, name, polyType, fields) (dataConstructors env) }
74 :: (MonadState CheckState m, MonadError MultipleErrors m)
76 -> ProperName 'TypeName
77 -> [(String, Maybe Kind)]
81addTypeSynonym moduleName name args ty kind = do
84 putEnv $ env { types = M.insert (Qualified (Just moduleName) name) (kind, TypeSynonym) (types env)
85 , typeSynonyms = M.insert (Qualified (Just moduleName) name) (args, ty) (typeSynonyms env) }
88 :: (MonadState CheckState m, MonadError MultipleErrors m)
92valueIsNotDefined moduleName name = do
94 case M.lookup (Qualified (Just moduleName) name) (names env) of
95 Just _ -> throwError . errorMessage $ RedefinedIdent name
99 :: (MonadState CheckState m)
105addValue moduleName name ty nameKind = do
107 putEnv (env { names = M.insert (Qualified (Just moduleName) name) (ty, nameKind, Defined) (names env) })
110 :: (MonadState CheckState m)
112 -> ProperName 'ClassName
113 -> [(String, Maybe Kind)]
115 -> [FunctionalDependency]
118addTypeClass moduleName pn args implies dependencies ds =
119 modify $ \st -> st { checkEnv = (checkEnv st) { typeClasses = M.insert (Qualified (Just moduleName) pn) newClass (typeClasses . checkEnv $ st) } }
121 newClass :: TypeClassData
123 TypeClassData { typeClassArguments = args
124 , typeClassMembers = map toPair ds
125 , typeClassSuperclasses = implies
126 , typeClassDependencies = dependencies
129 toPair (TypeDeclaration ident ty) = (ident, ty)
130 toPair (PositionedDeclaration _ _ d) = toPair d
131 toPair _ = internalError "Invalid declaration in TypeClassDeclaration"
133addTypeClassDictionaries
134 :: (MonadState CheckState m)
136 -> M.Map (Qualified (ProperName 'ClassName)) (M.Map (Qualified Ident) TypeClassDictionaryInScope)
138addTypeClassDictionaries mn entries =
139 modify $ \st -> st { checkEnv = (checkEnv st) { typeClassDictionaries = insertState st } }
140 where insertState st = M.insertWith (M.unionWith M.union) mn entries (typeClassDictionaries . checkEnv $ st)
142checkDuplicateTypeArguments
143 :: (MonadState CheckState m, MonadError MultipleErrors m)
146checkDuplicateTypeArguments args = for_ firstDup $ \dup ->
147 throwError . errorMessage $ DuplicateTypeArgument dup
149 firstDup :: Maybe String
150 firstDup = listToMaybe $ args \\ nub args
152checkTypeClassInstance
153 :: (MonadState CheckState m, MonadError MultipleErrors m, MonadWriter MultipleErrors m)
157checkTypeClassInstance _ (TypeVar _) = return ()
158checkTypeClassInstance _ (TypeLevelString _) = return ()
159checkTypeClassInstance _ (TypeConstructor ctor) = do
161 when (ctor `M.member` typeSynonyms env) . throwError . errorMessage $ TypeSynonymInstance
163checkTypeClassInstance m (TypeApp t1 t2) = checkTypeClassInstance m t1 >> checkTypeClassInstance m t2
164checkTypeClassInstance _ ty = throwError . errorMessage $ InvalidInstanceHead ty
167-- Check that type synonyms are fully-applied in a type
170 :: (MonadState CheckState m, MonadError MultipleErrors m)
173checkTypeSynonyms = void . replaceAllTypeSynonyms
176-- Type check all declarations in a module
178-- At this point, many declarations will have been desugared, but it is still necessary to
180-- * Kind-check all types and add them to the @Environment@
182-- * Type-check all values and add them to the @Environment@
184-- * Bring type class instances into scope
186-- * Process module imports
190 . (MonadSupply m, MonadState CheckState m, MonadError MultipleErrors m, MonadWriter MultipleErrors m)
195typeCheckAll moduleName _ = traverse go
197 go :: Declaration -> m Declaration
198 go (DataDeclaration dtype name args dctors) = do
199 warnAndRethrow (addHint (ErrorInTypeConstructor name)) $ do
200 when (dtype == Newtype) $ checkNewtype name dctors
201 checkDuplicateTypeArguments $ map fst args
202 ctorKind <- kindsOf True moduleName name args (concatMap snd dctors)
203 let args' = args `withKinds` ctorKind
204 addDataType moduleName dtype name args' dctors ctorKind
205 return $ DataDeclaration dtype name args dctors
206 go (d@(DataBindingGroupDeclaration tys)) = do
207 warnAndRethrow (addHint ErrorInDataBindingGroup) $ do
208 let syns = mapMaybe toTypeSynonym tys
209 let dataDecls = mapMaybe toDataDecl tys
210 (syn_ks, data_ks) <- kindsOfAll moduleName syns (map (\(_, name, args, dctors) -> (name, args, concatMap snd dctors)) dataDecls)
211 for_ (zip dataDecls data_ks) $ \((dtype, name, args, dctors), ctorKind) -> do
212 when (dtype == Newtype) $ checkNewtype name dctors
213 checkDuplicateTypeArguments $ map fst args
214 let args' = args `withKinds` ctorKind
215 addDataType moduleName dtype name args' dctors ctorKind
216 for_ (zip syns syn_ks) $ \((name, args, ty), kind) -> do
217 checkDuplicateTypeArguments $ map fst args
218 let args' = args `withKinds` kind
219 addTypeSynonym moduleName name args' ty kind
222 toTypeSynonym (TypeSynonymDeclaration nm args ty) = Just (nm, args, ty)
223 toTypeSynonym (PositionedDeclaration _ _ d') = toTypeSynonym d'
224 toTypeSynonym _ = Nothing
225 toDataDecl (DataDeclaration dtype nm args dctors) = Just (dtype, nm, args, dctors)
226 toDataDecl (PositionedDeclaration _ _ d') = toDataDecl d'
227 toDataDecl _ = Nothing
228 go (TypeSynonymDeclaration name args ty) = do
229 warnAndRethrow (addHint (ErrorInTypeSynonym name)) $ do
230 checkDuplicateTypeArguments $ map fst args
231 kind <- kindsOf False moduleName name args [ty]
232 let args' = args `withKinds` kind
233 addTypeSynonym moduleName name args' ty kind
234 return $ TypeSynonymDeclaration name args ty
235 go TypeDeclaration{} =
236 internalError "Type declarations should have been removed before typeCheckAlld"
237 go (ValueDeclaration name nameKind [] (Right val)) = do
239 warnAndRethrow (addHint (ErrorInValueDeclaration name)) $ do
240 val' <- checkExhaustiveExpr env moduleName val
241 valueIsNotDefined moduleName name
242 [(_, (val'', ty))] <- typesOf NonRecursiveBindingGroup moduleName [(name, val')]
243 addValue moduleName name ty nameKind
244 return $ ValueDeclaration name nameKind [] $ Right val''
245 go ValueDeclaration{} = internalError "Binders were not desugared"
246 go (BindingGroupDeclaration vals) = do
248 warnAndRethrow (addHint (ErrorInBindingGroup (map (\(ident, _, _) -> ident) vals))) $ do
249 for_ vals $ \(ident, _, _) ->
250 valueIsNotDefined moduleName ident
251 vals' <- mapM (thirdM (checkExhaustiveExpr env moduleName)) vals
252 tys <- typesOf RecursiveBindingGroup moduleName $ map (\(ident, _, ty) -> (ident, ty)) vals'
253 vals'' <- forM [ (name, val, nameKind, ty)
254 | (name, nameKind, _) <- vals'
255 , (name', (val, ty)) <- tys
257 ] $ \(name, val, nameKind, ty) -> do
258 addValue moduleName name ty nameKind
259 return (name, nameKind, val)
260 return $ BindingGroupDeclaration vals''
261 go (d@(ExternDataDeclaration name kind)) = do
263 putEnv $ env { types = M.insert (Qualified (Just moduleName) name) (kind, ExternData) (types env) }
265 go (d@(ExternDeclaration name ty)) = do
266 warnAndRethrow (addHint (ErrorInForeignImport name)) $ do
269 guardWith (errorMessage (ExpectedType ty kind)) $ kind == Star
270 case M.lookup (Qualified (Just moduleName) name) (names env) of
271 Just _ -> throwError . errorMessage $ RedefinedIdent name
272 Nothing -> putEnv (env { names = M.insert (Qualified (Just moduleName) name) (ty, External, Defined) (names env) })
274 go d@FixityDeclaration{} = return d
275 go d@ImportDeclaration{} = return d
276 go d@(TypeClassDeclaration pn args implies deps tys) = do
277 addTypeClass moduleName pn args implies deps tys
279 go (d@(TypeInstanceDeclaration dictName deps className tys body)) = rethrow (addHint (ErrorInInstance className tys)) $ do
280 traverse_ (checkTypeClassInstance moduleName) tys
281 forM_ deps $ traverse_ (checkTypeClassInstance moduleName) . constraintArgs
282 checkOrphanInstance dictName className tys
283 _ <- traverseTypeInstanceBody checkInstanceMembers body
284 let dict = TypeClassDictionaryInScope (Qualified (Just moduleName) dictName) [] className tys (Just deps)
285 addTypeClassDictionaries (Just moduleName) . M.singleton className $ M.singleton (tcdName dict) dict
287 go (PositionedDeclaration pos com d) =
288 warnAndRethrowWithPosition pos $ PositionedDeclaration pos com <$> go d
290 checkInstanceMembers :: [Declaration] -> m [Declaration]
291 checkInstanceMembers instDecls = do
292 let idents = sort . map head . group . map memberName $ instDecls
293 for_ (firstDuplicate idents) $ \ident ->
294 throwError . errorMessage $ DuplicateValueDeclaration ident
297 memberName :: Declaration -> Ident
298 memberName (ValueDeclaration ident _ _ _) = ident
299 memberName (PositionedDeclaration _ _ d) = memberName d
300 memberName _ = internalError "checkInstanceMembers: Invalid declaration in type instance definition"
302 firstDuplicate :: (Eq a) => [a] -> Maybe a
303 firstDuplicate (x : xs@(y : _))
305 | otherwise = firstDuplicate xs
306 firstDuplicate _ = Nothing
308 checkOrphanInstance :: Ident -> Qualified (ProperName 'ClassName) -> [Type] -> m ()
309 checkOrphanInstance dictName className@(Qualified (Just mn') _) tys'
310 | moduleName == mn' || any checkType tys' = return ()
311 | otherwise = throwError . errorMessage $ OrphanInstance dictName className tys'
313 checkType :: Type -> Bool
314 checkType (TypeVar _) = False
315 checkType (TypeConstructor (Qualified (Just mn'') _)) = moduleName == mn''
316 checkType (TypeConstructor (Qualified Nothing _)) = internalError "Unqualified type name in checkOrphanInstance"
317 checkType (TypeApp t1 _) = checkType t1
318 checkType _ = internalError "Invalid type in instance in checkOrphanInstance"
319 checkOrphanInstance _ _ _ = internalError "Unqualified class name in checkOrphanInstance"
321 checkNewtype :: ProperName 'TypeName -> [(ProperName 'ConstructorName, [Type])] -> m ()
322 checkNewtype _ [(_, [_])] = return ()
323 checkNewtype name _ = throwError . errorMessage $ InvalidNewtype name
326 -- This function adds the argument kinds for a type constructor so that they may appear in the externs file,
327 -- extracted from the kind of the type constructor itself.
329 withKinds :: [(String, Maybe Kind)] -> Kind -> [(String, Maybe Kind)]
331 withKinds (s@(_, Just _ ):ss) (FunKind _ k) = s : withKinds ss k
332 withKinds ( (s, Nothing):ss) (FunKind k1 k2) = (s, Just k1) : withKinds ss k2
333 withKinds _ _ = internalError "Invalid arguments to peelKinds"
336-- Type check an entire module and ensure all types and classes defined within the module that are
337-- required by exported members are also exported.
341 . (MonadSupply m, MonadState CheckState m, MonadError MultipleErrors m, MonadWriter MultipleErrors m)
344typeCheckModule (Module _ _ _ _ Nothing) =
345 internalError "exports should have been elaborated before typeCheckModule"
346typeCheckModule (Module ss coms mn decls (Just exps)) =
347 warnAndRethrow (addHint (ErrorInModule mn)) $ do
348 modify (\s -> s { checkCurrentModule = Just mn })
349 decls' <- typeCheckAll mn exps decls
351 checkTypesAreExported e
352 checkClassMembersAreExported e
353 checkClassesAreExported e
354 return $ Module ss coms mn decls' (Just exps)
357 checkMemberExport :: (Type -> [DeclarationRef]) -> DeclarationRef -> m ()
358 checkMemberExport extract dr@(TypeRef name dctors) = do
360 case M.lookup (Qualified (Just mn) name) (typeSynonyms env) of
362 Just (_, ty) -> checkExport dr extract ty
365 Just dctors' -> for_ dctors' $ \dctor ->
366 case M.lookup (Qualified (Just mn) dctor) (dataConstructors env) of
368 Just (_, _, ty, _) -> checkExport dr extract ty
370 checkMemberExport extract dr@(ValueRef name) = do
371 ty <- lookupVariable (Qualified (Just mn) name)
372 checkExport dr extract ty
373 checkMemberExport _ _ = return ()
375 checkExport :: DeclarationRef -> (Type -> [DeclarationRef]) -> Type -> m ()
376 checkExport dr extract ty = case filter (not . exported) (extract ty) of
378 hidden -> throwError . errorMessage $ TransitiveExportError dr (nubBy nubEq hidden)
380 exported e = any (exports e) exps
381 exports (TypeRef pn1 _) (TypeRef pn2 _) = pn1 == pn2
382 exports (ValueRef id1) (ValueRef id2) = id1 == id2
383 exports (TypeClassRef pn1) (TypeClassRef pn2) = pn1 == pn2
384 exports (PositionedDeclarationRef _ _ r1) r2 = exports r1 r2
385 exports r1 (PositionedDeclarationRef _ _ r2) = exports r1 r2
387 -- We avoid Eq for `nub`bing as the dctor part of `TypeRef` evaluates to
388 -- `error` for the values generated here (we don't need them anyway)
389 nubEq (TypeRef pn1 _) (TypeRef pn2 _) = pn1 == pn2
390 nubEq r1 r2 = r1 == r2
393 -- Check that all the type constructors defined in the current module that appear in member types
394 -- have also been exported from the module
395 checkTypesAreExported :: DeclarationRef -> m ()
396 checkTypesAreExported = checkMemberExport findTcons
398 findTcons :: Type -> [DeclarationRef]
399 findTcons = everythingOnTypes (++) go
401 go (TypeConstructor (Qualified (Just mn') name)) | mn' == mn = [TypeRef name (internalError "Data constructors unused in checkTypesAreExported")]
404 -- Check that all the classes defined in the current module that appear in member types have also
405 -- been exported from the module
406 checkClassesAreExported :: DeclarationRef -> m ()
407 checkClassesAreExported = checkMemberExport findClasses
409 findClasses :: Type -> [DeclarationRef]
410 findClasses = everythingOnTypes (++) go
412 go (ConstrainedType cs _) = mapMaybe (fmap TypeClassRef . extractCurrentModuleClass . constraintClass) cs
414 extractCurrentModuleClass :: Qualified (ProperName 'ClassName) -> Maybe (ProperName 'ClassName)
415 extractCurrentModuleClass (Qualified (Just mn') name) | mn == mn' = Just name
416 extractCurrentModuleClass _ = Nothing
418 checkClassMembersAreExported :: DeclarationRef -> m ()
419 checkClassMembersAreExported dr@(TypeClassRef name) = do
420 let members = ValueRef `map` head (mapMaybe findClassMembers decls)
421 let missingMembers = members \\ exps
422 unless (null missingMembers) $ throwError . errorMessage $ TransitiveExportError dr members
424 findClassMembers :: Declaration -> Maybe [Ident]
425 findClassMembers (TypeClassDeclaration name' _ _ _ ds) | name == name' = Just $ map extractMemberName ds
426 findClassMembers (PositionedDeclaration _ _ d) = findClassMembers d
427 findClassMembers _ = Nothing
428 extractMemberName :: Declaration -> Ident
429 extractMemberName (PositionedDeclaration _ _ d) = extractMemberName d
430 extractMemberName (TypeDeclaration memberName _) = memberName
431 extractMemberName _ = internalError "Unexpected declaration in typeclass member list"
432 checkClassMembersAreExported _ = return ()
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list