git.iko.soy/rowtype-yoga/purescript-native
on c3b4444 help sign in
342 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.Monad.State
35import Control.Monad.Error.Class (MonadError(..))
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 (onErrorMessages (ErrorInDataConstructor 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 let fields = [Ident ("value" ++ show n) | n <- [0..(length tys - 1)]]
61 putEnv $ env { dataConstructors = M.insert (Qualified (Just moduleName) dctor) (dtype, name, polyType, fields) (dataConstructors env) }
63addTypeSynonym :: ModuleName -> ProperName -> [(String, Maybe Kind)] -> Type -> Kind -> Check ()
64addTypeSynonym moduleName name args ty kind = do
65 env <- getEnv
66 checkTypeSynonyms ty
67 putEnv $ env { types = M.insert (Qualified (Just moduleName) name) (kind, TypeSynonym) (types env)
68 , typeSynonyms = M.insert (Qualified (Just moduleName) name) (args, ty) (typeSynonyms env) }
70valueIsNotDefined :: ModuleName -> Ident -> Check ()
71valueIsNotDefined moduleName name = do
72 env <- getEnv
73 case M.lookup (moduleName, name) (names env) of
74 Just _ -> throwError . errorMessage $ RedefinedIdent name
75 Nothing -> return ()
77addValue :: ModuleName -> Ident -> Type -> NameKind -> Check ()
78addValue moduleName name ty nameKind = do
79 env <- getEnv
80 putEnv (env { names = M.insert (moduleName, name) (ty, nameKind, Defined) (names env) })
82addTypeClass :: ModuleName -> ProperName -> [(String, Maybe Kind)] -> [Constraint] -> [Declaration] -> Check ()
83addTypeClass moduleName pn args implies ds =
84 let members = map toPair ds in
85 modify $ \st -> st { checkEnv = (checkEnv st) { typeClasses = M.insert (Qualified (Just moduleName) pn) (args, members, implies) (typeClasses . checkEnv $ st) } }
86 where
87 toPair (TypeDeclaration ident ty) = (ident, ty)
88 toPair (PositionedDeclaration _ _ d) = toPair d
89 toPair _ = error "Invalid declaration in TypeClassDeclaration"
91addTypeClassDictionaries :: Maybe ModuleName -> M.Map (Qualified Ident) TypeClassDictionaryInScope -> Check ()
92addTypeClassDictionaries mn entries =
93 modify $ \st -> st { checkEnv = (checkEnv st) { typeClassDictionaries = M.insertWith M.union mn entries (typeClassDictionaries . checkEnv $ st) } }
95checkDuplicateTypeArguments :: [String] -> Check ()
96checkDuplicateTypeArguments args = for_ firstDup $ \dup ->
97 throwError . errorMessage $ DuplicateTypeArgument 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 . errorMessage $ TypeSynonymInstance
107 return ()
108checkTypeClassInstance m (TypeApp t1 t2) = checkTypeClassInstance m t1 >> checkTypeClassInstance m t2
109checkTypeClassInstance _ ty = throwError . errorMessage $ InvalidInstanceHead 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 (onErrorMessages (ErrorInTypeConstructor 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 . errorMessage $ InvalidNewtype
148 checkNewtype _ = throwError . errorMessage $ InvalidNewtype
149 go (d@(DataBindingGroupDeclaration tys) : rest) = 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 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 (onErrorMessages (ErrorInTypeSynonym 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 (onErrorMessages (ErrorInValueDeclaration 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 (onErrorMessages (ErrorInBindingGroup (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 name ty) : rest) = do
210 rethrow (onErrorMessages (ErrorInForeignImport name)) $ do
211 env <- getEnv
212 kind <- kindOf moduleName ty
213 guardWith (errorMessage (ExpectedType kind)) $ kind == Star
214 case M.lookup (moduleName, name) (names env) of
215 Just _ -> throwError . errorMessage $ RedefinedIdent name
216 Nothing -> putEnv (env { names = M.insert (moduleName, name) (ty, External, 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 (errorMessage (OrphanFixityDeclaration name)) $ M.member (moduleName, Op name) $ names env
223 return $ d : ds
224 go (d@(ImportDeclaration importedModule _ _) : rest) = do
225 instances <- lookupTypeClassDictionaries $ Just importedModule
226 addTypeClassDictionaries (Just moduleName) instances
227 ds <- go rest
228 return $ d : ds
229 go (d@(TypeClassDeclaration pn args implies tys) : rest) = do
230 addTypeClass moduleName pn args implies tys
231 ds <- go rest
232 return $ d : ds
233 go (d@(TypeInstanceDeclaration dictName deps className tys _) : rest) = do
234 goInstance d dictName deps className tys rest
235 go (d@(ExternInstanceDeclaration dictName deps className tys) : rest) = do
236 goInstance d dictName deps className tys rest
237 go (PositionedDeclaration pos com d : rest) =
238 rethrowWithPosition pos $ do
239 (d' : rest') <- go (d : rest)
240 return (PositionedDeclaration pos com d' : rest')
241 goInstance :: Declaration -> Ident -> [Constraint] -> Qualified ProperName -> [Type] -> [Declaration] -> Check [Declaration]
242 goInstance d dictName deps className tys rest = do
243 mapM_ (checkTypeClassInstance moduleName) tys
244 forM_ deps $ mapM_ (checkTypeClassInstance moduleName) . snd
245 let dict = TypeClassDictionaryInScope (Qualified (Just moduleName) dictName) className tys (Just deps) TCDRegular isInstanceExported
246 addTypeClassDictionaries (Just moduleName) $ M.singleton (canonicalizeDictionary dict) dict
247 ds <- go rest
248 return $ d : ds
250 where
252 isInstanceExported :: Bool
253 isInstanceExported = any exportsInstance exps
255 exportsInstance :: DeclarationRef -> Bool
256 exportsInstance (TypeInstanceRef name) | name == dictName = True
257 exportsInstance (PositionedDeclarationRef _ _ r) = exportsInstance r
258 exportsInstance _ = False
260 -- |
261 -- This function adds the argument kinds for a type constructor so that they may appear in the externs file,
262 -- extracted from the kind of the type constructor itself.
263 --
264 withKinds :: [(String, Maybe Kind)] -> Kind -> [(String, Maybe Kind)]
265 withKinds [] _ = []
266 withKinds (s@(_, Just _ ):ss) (FunKind _ k) = s : withKinds ss k
267 withKinds ( (s, Nothing):ss) (FunKind k1 k2) = (s, Just k1) : withKinds ss k2
268 withKinds _ _ = error "Invalid arguments to peelKinds"
270-- |
271-- Type check an entire module and ensure all types and classes defined within the module that are
272-- required by exported members are also exported.
273--
274typeCheckModule :: Maybe ModuleName -> Module -> Check Module
275typeCheckModule _ (Module _ _ _ Nothing) = error "exports should have been elaborated"
276typeCheckModule mainModuleName (Module coms mn decls (Just exps)) = rethrow (onErrorMessages (ErrorInModule mn)) $ do
277 modify (\s -> s { checkCurrentModule = Just mn })
278 decls' <- typeCheckAll mainModuleName mn exps decls
279 forM_ exps $ \e -> do
280 checkTypesAreExported e
281 checkClassMembersAreExported e
282 checkClassesAreExported e
283 return $ Module coms mn decls' (Just exps)
284 where
286 checkMemberExport :: (Type -> [DeclarationRef]) -> DeclarationRef -> Check ()
287 checkMemberExport extract dr@(ValueRef name) = do
288 ty <- lookupVariable mn (Qualified (Just mn) name)
289 case filter (not . exported) (extract ty) of
290 [] -> return ()
291 hidden -> throwError . errorMessage $ TransitiveExportError dr hidden
292 where
293 exported e = any (exports e) exps
294 exports (TypeRef pn1 _) (TypeRef pn2 _) = pn1 == pn2
295 exports (ValueRef id1) (ValueRef id2) = id1 == id2
296 exports (TypeClassRef pn1) (TypeClassRef pn2) = pn1 == pn2
297 exports (TypeInstanceRef id1) (TypeInstanceRef id2) = id1 == id2
298 exports (PositionedDeclarationRef _ _ r1) r2 = exports r1 r2
299 exports r1 (PositionedDeclarationRef _ _ r2) = exports r1 r2
300 exports _ _ = False
301 checkMemberExport _ _ = return ()
303 -- Check that all the type constructors defined in the current module that appear in member types
304 -- have also been exported from the module
305 checkTypesAreExported :: DeclarationRef -> Check ()
306 checkTypesAreExported = checkMemberExport findTcons
307 where
308 findTcons :: Type -> [DeclarationRef]
309 findTcons = everythingOnTypes (++) go
310 where
311 go (TypeConstructor (Qualified (Just mn') name)) | mn' == mn = [TypeRef name (error "Data constructors unused in checkTypesAreExported")]
312 go _ = []
314 -- Check that all the classes defined in the current module that appear in member types have also
315 -- been exported from the module
316 checkClassesAreExported :: DeclarationRef -> Check ()
317 checkClassesAreExported = checkMemberExport findClasses
318 where
319 findClasses :: Type -> [DeclarationRef]
320 findClasses = everythingOnTypes (++) go
321 where
322 go (ConstrainedType cs _) = mapMaybe (fmap TypeClassRef . extractCurrentModuleClass . fst) cs
323 go _ = []
324 extractCurrentModuleClass :: Qualified ProperName -> Maybe ProperName
325 extractCurrentModuleClass (Qualified (Just mn') name) | mn == mn' = Just name
326 extractCurrentModuleClass _ = Nothing
328 checkClassMembersAreExported :: DeclarationRef -> Check ()
329 checkClassMembersAreExported dr@(TypeClassRef name) = do
330 let members = ValueRef `map` head (mapMaybe findClassMembers decls)
331 let missingMembers = members \\ exps
332 unless (null missingMembers) $ throwError . errorMessage $ TransitiveExportError dr members
333 where
334 findClassMembers :: Declaration -> Maybe [Ident]
335 findClassMembers (TypeClassDeclaration name' _ _ ds) | name == name' = Just $ map extractMemberName ds
336 findClassMembers (PositionedDeclaration _ _ d) = findClassMembers d
337 findClassMembers _ = Nothing
338 extractMemberName :: Declaration -> Ident
339 extractMemberName (PositionedDeclaration _ _ d) = extractMemberName d
340 extractMemberName (TypeDeclaration memberName _) = memberName
341 extractMemberName _ = error "Unexpected declaration in typeclass member list"
342 checkClassMembersAreExported _ = return ()