[project @ 1998-12-02 13:17:09 by simonm]
[ghc-hetmet.git] / ghc / compiler / typecheck / TcForeign.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1998
3 %
4 \section[TcForeign]{Typechecking \tr{foreign} declarations}
5
6 A foreign declaration is used to either give an externally
7 implemented function a Haskell type (and calling interface) or
8 give a Haskell function an external calling interface. Either way,
9 the range of argument and result types these functions can accommodate
10 is restricted to what the outside world understands (read C), and this
11 module checks to see if a foreign declaration has got a legal type.
12
13 \begin{code}
14 module TcForeign 
15         ( 
16           tcForeignImports
17         , tcForeignExports
18         ) where
19
20 #include "HsVersions.h"
21
22 import HsSyn            ( HsDecl(..), ForeignDecl(..), HsExpr(..),
23                           ExtName(..), isDynamic, MonoBinds(..),
24                           OutPat(..), ForKind(..)
25                         )
26 import RnHsSyn          ( RenamedHsDecl, RenamedForeignDecl )
27
28 import TcMonad
29 import TcEnv            ( tcLookupClassByKey, newLocalId, tcLookupGlobalValue )
30 import TcType           ( tcInstTcType, typeToTcType, tcSplitRhoTy, zonkTcTypeToType )
31 import TcMonoType       ( tcHsType )
32 import TcHsSyn          ( TcMonoBinds, maybeBoxedPrimType, TypecheckedForeignDecl, TcIdOcc(..),
33                           TcForeignExportDecl )
34 import TcExpr           ( tcId, tcPolyExpr )                    
35 import Inst             ( emptyLIE, LIE, plusLIE )
36 import CoreSyn
37
38 import ErrUtils         ( Message )
39 import Id               ( Id, idName, mkUserId )
40 import Name             ( nameOccName )
41 import Type             ( splitFunTys
42                         , splitTyConApp_maybe
43                         , splitForAllTys
44                         , splitRhoTy
45                         , isForAllTy
46                         , mkForAllTys
47                         )
48
49 import TysWiredIn       ( isFFIArgumentTy, isFFIResultTy, 
50                           isFFIExternalTy, isAddrTy
51                         )
52 import Type             ( Type )
53 import Unique
54 import Outputable
55 import Util
56 import CmdLineOpts      ( opt_GlasgowExts )
57 import Maybes           ( maybeToBool )
58
59 \end{code}
60
61 \begin{code}
62 tcForeignImports :: [RenamedHsDecl] -> TcM s ([Id], [TypecheckedForeignDecl])
63 tcForeignImports decls = 
64    mapAndUnzipTc tcFImport [ foreign_decl | ForD foreign_decl <- decls, isForeignImport foreign_decl]
65
66 tcForeignExports :: [RenamedHsDecl] -> TcM s (LIE s, TcMonoBinds s, [TcForeignExportDecl s])
67 tcForeignExports decls = 
68    foldlTc combine (emptyLIE, EmptyMonoBinds, [])
69                    [ foreign_decl | ForD foreign_decl <- decls, isForeignExport foreign_decl]
70   where
71    combine (lie, binds, fs) fe = 
72        tcFExport fe `thenTc ` \ (a_lie, b, f) ->
73        returnTc (lie `plusLIE` a_lie, b `AndMonoBinds` binds, f:fs)
74
75 -- defines a binding
76 isForeignImport :: ForeignDecl name -> Bool
77 isForeignImport (ForeignDecl _ k _ dyn _ _) =
78   case k of
79     FoImport _ -> True
80     FoExport   -> case dyn of { Dynamic -> True ; _ -> False }
81     FoLabel    -> True
82
83 -- exports a binding
84 isForeignExport :: ForeignDecl name -> Bool
85 isForeignExport (ForeignDecl _ FoExport _ ext_nm _ _) = not (isDynamic ext_nm)
86 isForeignExport _                                     = False
87
88 \end{code}
89
90 \begin{code}
91 tcFImport :: RenamedForeignDecl -> TcM s (Id, TypecheckedForeignDecl)
92 tcFImport fo@(ForeignDecl nm FoExport hs_ty Dynamic cconv src_loc) =
93    tcAddSrcLoc src_loc               $
94    tcAddErrCtxt (foreignDeclCtxt fo) $
95    tcHsType hs_ty                   `thenTc`    \ sig_ty ->
96    let
97       -- drop the foralls before inspecting the structure
98       -- of the foreign type.
99     (_, t_ty) = splitForAllTys sig_ty
100    in
101    case splitFunTys t_ty of
102      (arg_tys, res_ty) -> 
103         checkForeignExport True t_ty arg_tys res_ty `thenTc_`
104         let i = (mkUserId nm sig_ty) in
105         returnTc (i, (ForeignDecl i FoExport undefined Dynamic cconv src_loc))
106
107 tcFImport fo@(ForeignDecl nm FoLabel hs_ty ext_nm cconv src_loc) =
108    tcAddSrcLoc src_loc               $
109    tcAddErrCtxt (foreignDeclCtxt fo) $
110    tcHsType hs_ty                   `thenTc`    \ sig_ty ->
111    let
112       -- drop the foralls before inspecting the structure
113       -- of the foreign type.
114     (_, t_ty) = splitForAllTys sig_ty
115    in
116    check (isAddrTy t_ty) (illegalForeignTyErr False{-result-} sig_ty) `thenTc_`
117    let i = (mkUserId nm sig_ty) in
118    returnTc (i, (ForeignDecl i FoLabel undefined ext_nm cconv src_loc))
119
120 tcFImport fo@(ForeignDecl nm imp_exp hs_ty ext_nm cconv src_loc) =
121    tcAddSrcLoc src_loc               $
122    tcAddErrCtxt (foreignDeclCtxt fo) $
123
124    tcHsType hs_ty                    `thenTc` \ ty ->
125     -- Check that the type has the right shape
126     -- and that the argument and result types are acceptable.
127    let
128       -- drop the foralls before inspecting the structure
129       -- of the foreign type.
130     (_, t_ty) = splitForAllTys ty
131    in
132    case splitFunTys t_ty of
133      (arg_tys, res_ty) ->
134         checkForeignImport (isDynamic ext_nm) ty arg_tys res_ty `thenTc_`
135         let i = (mkUserId nm ty) in
136         returnTc (i, (ForeignDecl i imp_exp undefined ext_nm cconv src_loc))
137
138 tcFExport :: RenamedForeignDecl -> TcM s (LIE s, TcMonoBinds s, TcForeignExportDecl s)
139 tcFExport fo@(ForeignDecl nm imp_exp hs_ty ext_nm cconv src_loc) =
140    tcAddSrcLoc src_loc               $
141    tcAddErrCtxt (foreignDeclCtxt fo) $
142
143    tcHsType hs_ty                      `thenTc` \ sig_ty ->
144    let sig_tc_ty = typeToTcType sig_ty in
145    tcPolyExpr (HsVar nm) sig_tc_ty     `thenTc`    \ (rhs, lie, _, _, _) ->
146
147    let
148       -- drop the foralls before inspecting the structure
149       -- of the foreign type.
150     (_, t_ty) = splitForAllTys sig_ty
151    in
152    case splitFunTys t_ty of
153      (arg_tys, res_ty) -> 
154         checkForeignExport False t_ty arg_tys res_ty `thenTc_`
155           -- we're exporting a function, but at a type possibly more constrained
156           -- than its declared/inferred type. Hence the need
157           -- to create a local binding which will call the exported function
158           -- at a particular type (and, maybe, overloading).
159         newLocalId (nameOccName nm) sig_tc_ty   `thenNF_Tc` \ i ->
160         let
161             i2    = TcId i
162             bind  = VarMonoBind i2 rhs
163         in
164         returnTc (lie, bind, ForeignDecl i2 imp_exp undefined ext_nm cconv src_loc)
165         --                                          ^^^^^^^^^
166         -- ToDo: fill the type field in with something sensible.
167
168 \end{code}
169
170
171 \begin{code}
172 checkForeignImport :: Bool -> Type -> [Type] -> Type -> TcM s ()
173 checkForeignImport is_dynamic ty args res
174  | is_dynamic =
175     -- * first arg has got to be an Addr
176    case args of
177      []     -> check False (illegalForeignTyErr True{-Arg-} ty)
178      (x:xs) ->
179         check (isAddrTy x) (illegalForeignTyErr True{-Arg-} ty) `thenTc_`
180         mapTc (checkForeignArg isFFIArgumentTy) xs              `thenTc_`
181         checkForeignRes (isFFIResultTy) res
182  | otherwise =
183      mapTc (checkForeignArg isFFIArgumentTy) args               `thenTc_`
184      checkForeignRes (isFFIResultTy) res
185
186 checkForeignExport :: Bool -> Type -> [Type] -> Type -> TcM s ()
187 checkForeignExport is_dynamic ty args res
188  | is_dynamic = 
189     -- * the first (and only!) arg has got to be a function type
190     -- * result type is an Addr
191    case args of
192      [arg]  ->
193         case splitFunTys arg of
194            (arg_tys, res_ty) -> 
195                 mapTc (checkForeignArg isFFIExternalTy) arg_tys `thenTc_`
196                 checkForeignRes (isFFIResultTy) res_ty          `thenTc_`
197                 checkForeignRes (isAddrTy) res
198      _      -> check False (illegalForeignTyErr True{-Arg-} ty)
199  | otherwise =
200      mapTc (checkForeignArg isFFIExternalTy) args               `thenTc_`
201      checkForeignRes (isFFIResultTy) res
202  
203 check :: Bool -> Message -> TcM s ()
204 check True _       = returnTc ()
205 check _    the_err = addErrTc the_err `thenNF_Tc_` returnTc ()
206
207 checkForeignArg :: (Type -> Bool) -> Type -> TcM s ()
208 checkForeignArg pred ty = check (pred ty) (illegalForeignTyErr True{-Arg-} ty)
209
210 -- Check that the type has the form 
211 --    (IO t) or (t) , and that t satisfies the given predicate.
212 --
213 checkForeignRes :: (Type -> Bool) -> Type -> TcM s ()
214 checkForeignRes pred_res_ty ty =
215  case (splitTyConApp_maybe ty) of
216     Just (io, [res_ty]) 
217         | (getUnique io) == ioTyConKey && pred_res_ty res_ty 
218         -> returnTc ()
219     _   
220         | pred_res_ty ty -> returnTc ()
221         | otherwise      -> check False (illegalForeignTyErr False{-Res-} ty)
222
223 \end{code}
224
225 Warnings
226
227 \begin{code}
228 illegalForeignTyErr isArg ty
229   = hang (hsep [ptext SLIT("Unacceptable"), arg_or_res, ptext SLIT("type in foreign declaration:")])
230          4 (hsep [ppr ty])
231   where
232    arg_or_res
233     | isArg     = ptext SLIT("argument")
234     | otherwise = ptext SLIT("result")
235
236 foreignDeclCtxt fo = 
237  hang (ptext SLIT("When checking declaration:"))
238   4   (ppr fo)
239
240 \end{code}