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 (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 (moduleName, name) (ty, nameKind, Defined) (names env) })
110 :: (MonadState CheckState m)
112 -> ProperName 'ClassName
113 -> [(String, Maybe Kind)]
117addTypeClass moduleName pn args implies ds =
118 let members = map toPair ds in
119 modify $ \st -> st { checkEnv = (checkEnv st) { typeClasses = M.insert (Qualified (Just moduleName) pn) (args, members, implies) (typeClasses . checkEnv $ st) } }
121 toPair (TypeDeclaration ident ty) = (ident, ty)
122 toPair (PositionedDeclaration _ _ d) = toPair d
123 toPair _ = internalError "Invalid declaration in TypeClassDeclaration"
125addTypeClassDictionaries
126 :: (MonadState CheckState m)
128 -> M.Map (Qualified (ProperName 'ClassName)) (M.Map (Qualified Ident) TypeClassDictionaryInScope)
130addTypeClassDictionaries mn entries =
131 modify $ \st -> st { checkEnv = (checkEnv st) { typeClassDictionaries = insertState st } }
132 where insertState st = M.insertWith (M.unionWith M.union) mn entries (typeClassDictionaries . checkEnv $ st)
134checkDuplicateTypeArguments
135 :: (MonadState CheckState m, MonadError MultipleErrors m)
138checkDuplicateTypeArguments args = for_ firstDup $ \dup ->
139 throwError . errorMessage $ DuplicateTypeArgument dup
141 firstDup :: Maybe String
142 firstDup = listToMaybe $ args \\ nub args
144checkTypeClassInstance
145 :: (MonadState CheckState m, MonadError MultipleErrors m, MonadWriter MultipleErrors m)
149checkTypeClassInstance _ (TypeVar _) = return ()
150checkTypeClassInstance _ (TypeLevelString _) = return ()
151checkTypeClassInstance _ (TypeConstructor ctor) = do
153 when (ctor `M.member` typeSynonyms env) . throwError . errorMessage $ TypeSynonymInstance
155checkTypeClassInstance m (TypeApp t1 t2) = checkTypeClassInstance m t1 >> checkTypeClassInstance m t2
156checkTypeClassInstance _ ty = throwError . errorMessage $ InvalidInstanceHead ty
159-- Check that type synonyms are fully-applied in a type
162 :: (MonadState CheckState m, MonadError MultipleErrors m)
165checkTypeSynonyms = void . replaceAllTypeSynonyms
168-- Type check all declarations in a module
170-- At this point, many declarations will have been desugared, but it is still necessary to
172-- * Kind-check all types and add them to the @Environment@
174-- * Type-check all values and add them to the @Environment@
176-- * Bring type class instances into scope
178-- * Process module imports
182 . (MonadSupply m, MonadState CheckState m, MonadError MultipleErrors m, MonadWriter MultipleErrors m)
187typeCheckAll moduleName _ = traverse go
189 go :: Declaration -> m Declaration
190 go (DataDeclaration dtype name args dctors) = do
191 warnAndRethrow (addHint (ErrorInTypeConstructor name)) $ do
192 when (dtype == Newtype) $ checkNewtype name dctors
193 checkDuplicateTypeArguments $ map fst args
194 ctorKind <- kindsOf True moduleName name args (concatMap snd dctors)
195 let args' = args `withKinds` ctorKind
196 addDataType moduleName dtype name args' dctors ctorKind
197 return $ DataDeclaration dtype name args dctors
198 go (d@(DataBindingGroupDeclaration tys)) = do
199 warnAndRethrow (addHint ErrorInDataBindingGroup) $ do
200 let syns = mapMaybe toTypeSynonym tys
201 let dataDecls = mapMaybe toDataDecl tys
202 (syn_ks, data_ks) <- kindsOfAll moduleName syns (map (\(_, name, args, dctors) -> (name, args, concatMap snd dctors)) dataDecls)
203 for_ (zip dataDecls data_ks) $ \((dtype, name, args, dctors), ctorKind) -> do
204 when (dtype == Newtype) $ checkNewtype name dctors
205 checkDuplicateTypeArguments $ map fst args
206 let args' = args `withKinds` ctorKind
207 addDataType moduleName dtype name args' dctors ctorKind
208 for_ (zip syns syn_ks) $ \((name, args, ty), kind) -> do
209 checkDuplicateTypeArguments $ map fst args
210 let args' = args `withKinds` kind
211 addTypeSynonym moduleName name args' ty kind
214 toTypeSynonym (TypeSynonymDeclaration nm args ty) = Just (nm, args, ty)
215 toTypeSynonym (PositionedDeclaration _ _ d') = toTypeSynonym d'
216 toTypeSynonym _ = Nothing
217 toDataDecl (DataDeclaration dtype nm args dctors) = Just (dtype, nm, args, dctors)
218 toDataDecl (PositionedDeclaration _ _ d') = toDataDecl d'
219 toDataDecl _ = Nothing
220 go (TypeSynonymDeclaration name args ty) = do
221 warnAndRethrow (addHint (ErrorInTypeSynonym name)) $ do
222 checkDuplicateTypeArguments $ map fst args
223 kind <- kindsOf False moduleName name args [ty]
224 let args' = args `withKinds` kind
225 addTypeSynonym moduleName name args' ty kind
226 return $ TypeSynonymDeclaration name args ty
227 go TypeDeclaration{} =
228 internalError "Type declarations should have been removed before typeCheckAlld"
229 go (ValueDeclaration name nameKind [] (Right val)) = do
231 warnAndRethrow (addHint (ErrorInValueDeclaration name)) $ do
232 val' <- checkExhaustiveExpr env moduleName val
233 valueIsNotDefined moduleName name
234 [(_, (val'', ty))] <- typesOf NonRecursiveBindingGroup moduleName [(name, val')]
235 addValue moduleName name ty nameKind
236 return $ ValueDeclaration name nameKind [] $ Right val''
237 go ValueDeclaration{} = internalError "Binders were not desugared"
238 go (BindingGroupDeclaration vals) = do
240 warnAndRethrow (addHint (ErrorInBindingGroup (map (\(ident, _, _) -> ident) vals))) $ do
241 for_ vals $ \(ident, _, _) ->
242 valueIsNotDefined moduleName ident
243 vals' <- mapM (thirdM (checkExhaustiveExpr env moduleName)) vals
244 tys <- typesOf RecursiveBindingGroup moduleName $ map (\(ident, _, ty) -> (ident, ty)) vals'
245 vals'' <- forM [ (name, val, nameKind, ty)
246 | (name, nameKind, _) <- vals'
247 , (name', (val, ty)) <- tys
249 ] $ \(name, val, nameKind, ty) -> do
250 addValue moduleName name ty nameKind
251 return (name, nameKind, val)
252 return $ BindingGroupDeclaration vals''
253 go (d@(ExternDataDeclaration name kind)) = do
255 putEnv $ env { types = M.insert (Qualified (Just moduleName) name) (kind, ExternData) (types env) }
257 go (d@(ExternDeclaration name ty)) = do
258 warnAndRethrow (addHint (ErrorInForeignImport name)) $ do
261 guardWith (errorMessage (ExpectedType ty kind)) $ kind == Star
262 case M.lookup (moduleName, name) (names env) of
263 Just _ -> throwError . errorMessage $ RedefinedIdent name
264 Nothing -> putEnv (env { names = M.insert (moduleName, name) (ty, External, Defined) (names env) })
266 go d@FixityDeclaration{} = return d
267 go d@ImportDeclaration{} = return d
268 go d@(TypeClassDeclaration pn args implies tys) = do
269 addTypeClass moduleName pn args implies tys
271 go (d@(TypeInstanceDeclaration dictName deps className tys body)) = rethrow (addHint (ErrorInInstance className tys)) $ do
272 traverse_ (checkTypeClassInstance moduleName) tys
273 forM_ deps $ traverse_ (checkTypeClassInstance moduleName) . constraintArgs
274 checkOrphanInstance dictName className tys
275 _ <- traverseTypeInstanceBody checkInstanceMembers body
276 let dict = TypeClassDictionaryInScope (Qualified (Just moduleName) dictName) [] className tys (Just deps)
277 addTypeClassDictionaries (Just moduleName) . M.singleton className $ M.singleton (tcdName dict) dict
279 go (PositionedDeclaration pos com d) =
280 warnAndRethrowWithPosition pos $ PositionedDeclaration pos com <$> go d
282 checkInstanceMembers :: [Declaration] -> m [Declaration]
283 checkInstanceMembers instDecls = do
284 let idents = sort . map head . group . map memberName $ instDecls
285 for_ (firstDuplicate idents) $ \ident ->
286 throwError . errorMessage $ DuplicateValueDeclaration ident
289 memberName :: Declaration -> Ident
290 memberName (ValueDeclaration ident _ _ _) = ident
291 memberName (PositionedDeclaration _ _ d) = memberName d
292 memberName _ = internalError "checkInstanceMembers: Invalid declaration in type instance definition"
294 firstDuplicate :: (Eq a) => [a] -> Maybe a
295 firstDuplicate (x : xs@(y : _))
297 | otherwise = firstDuplicate xs
298 firstDuplicate _ = Nothing
300 checkOrphanInstance :: Ident -> Qualified (ProperName 'ClassName) -> [Type] -> m ()
301 checkOrphanInstance dictName className@(Qualified (Just mn') _) tys'
302 | moduleName == mn' || any checkType tys' = return ()
303 | otherwise = throwError . errorMessage $ OrphanInstance dictName className tys'
305 checkType :: Type -> Bool
306 checkType (TypeVar _) = False
307 checkType (TypeConstructor (Qualified (Just mn'') _)) = moduleName == mn''
308 checkType (TypeConstructor (Qualified Nothing _)) = internalError "Unqualified type name in checkOrphanInstance"
309 checkType (TypeApp t1 _) = checkType t1
310 checkType _ = internalError "Invalid type in instance in checkOrphanInstance"
311 checkOrphanInstance _ _ _ = internalError "Unqualified class name in checkOrphanInstance"
313 checkNewtype :: ProperName 'TypeName -> [(ProperName 'ConstructorName, [Type])] -> m ()
314 checkNewtype _ [(_, [_])] = return ()
315 checkNewtype name _ = throwError . errorMessage $ InvalidNewtype name
318 -- This function adds the argument kinds for a type constructor so that they may appear in the externs file,
319 -- extracted from the kind of the type constructor itself.
321 withKinds :: [(String, Maybe Kind)] -> Kind -> [(String, Maybe Kind)]
323 withKinds (s@(_, Just _ ):ss) (FunKind _ k) = s : withKinds ss k
324 withKinds ( (s, Nothing):ss) (FunKind k1 k2) = (s, Just k1) : withKinds ss k2
325 withKinds _ _ = internalError "Invalid arguments to peelKinds"
328-- Type check an entire module and ensure all types and classes defined within the module that are
329-- required by exported members are also exported.
333 . (MonadSupply m, MonadState CheckState m, MonadError MultipleErrors m, MonadWriter MultipleErrors m)
336typeCheckModule (Module _ _ _ _ Nothing) =
337 internalError "exports should have been elaborated before typeCheckModule"
338typeCheckModule (Module ss coms mn decls (Just exps)) =
339 warnAndRethrow (addHint (ErrorInModule mn)) $ do
340 modify (\s -> s { checkCurrentModule = Just mn })
341 decls' <- typeCheckAll mn exps decls
343 checkTypesAreExported e
344 checkClassMembersAreExported e
345 checkClassesAreExported e
346 return $ Module ss coms mn decls' (Just exps)
349 checkMemberExport :: (Type -> [DeclarationRef]) -> DeclarationRef -> m ()
350 checkMemberExport extract dr@(TypeRef name dctors) = do
352 case M.lookup (Qualified (Just mn) name) (typeSynonyms env) of
354 Just (_, ty) -> checkExport dr extract ty
357 Just dctors' -> for_ dctors' $ \dctor ->
358 case M.lookup (Qualified (Just mn) dctor) (dataConstructors env) of
360 Just (_, _, ty, _) -> checkExport dr extract ty
362 checkMemberExport extract dr@(ValueRef name) = do
363 ty <- lookupVariable mn (Qualified (Just mn) name)
364 checkExport dr extract ty
365 checkMemberExport _ _ = return ()
367 checkExport :: DeclarationRef -> (Type -> [DeclarationRef]) -> Type -> m ()
368 checkExport dr extract ty = case filter (not . exported) (extract ty) of
370 hidden -> throwError . errorMessage $ TransitiveExportError dr (nubBy nubEq hidden)
372 exported e = any (exports e) exps
373 exports (TypeRef pn1 _) (TypeRef pn2 _) = pn1 == pn2
374 exports (ValueRef id1) (ValueRef id2) = id1 == id2
375 exports (TypeClassRef pn1) (TypeClassRef pn2) = pn1 == pn2
376 exports (PositionedDeclarationRef _ _ r1) r2 = exports r1 r2
377 exports r1 (PositionedDeclarationRef _ _ r2) = exports r1 r2
379 -- We avoid Eq for `nub`bing as the dctor part of `TypeRef` evaluates to
380 -- `error` for the values generated here (we don't need them anyway)
381 nubEq (TypeRef pn1 _) (TypeRef pn2 _) = pn1 == pn2
382 nubEq r1 r2 = r1 == r2
385 -- Check that all the type constructors defined in the current module that appear in member types
386 -- have also been exported from the module
387 checkTypesAreExported :: DeclarationRef -> m ()
388 checkTypesAreExported = checkMemberExport findTcons
390 findTcons :: Type -> [DeclarationRef]
391 findTcons = everythingOnTypes (++) go
393 go (TypeConstructor (Qualified (Just mn') name)) | mn' == mn = [TypeRef name (internalError "Data constructors unused in checkTypesAreExported")]
396 -- Check that all the classes defined in the current module that appear in member types have also
397 -- been exported from the module
398 checkClassesAreExported :: DeclarationRef -> m ()
399 checkClassesAreExported = checkMemberExport findClasses
401 findClasses :: Type -> [DeclarationRef]
402 findClasses = everythingOnTypes (++) go
404 go (ConstrainedType cs _) = mapMaybe (fmap TypeClassRef . extractCurrentModuleClass . constraintClass) cs
406 extractCurrentModuleClass :: Qualified (ProperName 'ClassName) -> Maybe (ProperName 'ClassName)
407 extractCurrentModuleClass (Qualified (Just mn') name) | mn == mn' = Just name
408 extractCurrentModuleClass _ = Nothing
410 checkClassMembersAreExported :: DeclarationRef -> m ()
411 checkClassMembersAreExported dr@(TypeClassRef name) = do
412 let members = ValueRef `map` head (mapMaybe findClassMembers decls)
413 let missingMembers = members \\ exps
414 unless (null missingMembers) $ throwError . errorMessage $ TransitiveExportError dr members
416 findClassMembers :: Declaration -> Maybe [Ident]
417 findClassMembers (TypeClassDeclaration name' _ _ ds) | name == name' = Just $ map extractMemberName ds
418 findClassMembers (PositionedDeclaration _ _ d) = findClassMembers d
419 findClassMembers _ = Nothing
420 extractMemberName :: Declaration -> Ident
421 extractMemberName (PositionedDeclaration _ _ d) = extractMemberName d
422 extractMemberName (TypeDeclaration memberName _) = memberName
423 extractMemberName _ = internalError "Unexpected declaration in typeclass member list"
424 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