27c6c1497de1862b7ae14c2055520034d6e5f483
[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(Dynamic), isDynamicExtName, MonoBinds(..),
24                           OutPat(..), ForKind(..)
25                         )
26 import RnHsSyn          ( RenamedHsDecl, RenamedForeignDecl )
27
28 import TcMonad
29 import TcEnv            ( newLocalId )
30 import TcType           ( typeToTcType, tcSplitRhoTy, zonkTcTypeToType )
31 import TcMonoType       ( tcHsTopBoxedType )
32 import TcHsSyn          ( TcMonoBinds, TypecheckedForeignDecl,
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, mkVanillaId )
40 import Name             ( nameOccName )
41 import Type             ( splitFunTys
42                         , splitTyConApp_maybe
43                         , splitForAllTys
44                         , splitRhoTy
45                         , isForAllTy
46                         , mkForAllTys
47                         )
48 import PprType          ( {- instance Outputable Type -} )
49
50 import TysWiredIn       ( isFFIArgumentTy, isFFIResultTy, 
51                           isFFIExternalTy, isAddrTy
52                         )
53 import Type             ( Type )
54 import Unique
55 import Outputable
56 import Util
57 import CmdLineOpts      ( opt_GlasgowExts )
58 import Maybes           ( maybeToBool )
59
60 \end{code}
61
62 \begin{code}
63 tcForeignImports :: [RenamedHsDecl] -> TcM s ([Id], [TypecheckedForeignDecl])
64 tcForeignImports decls = 
65    mapAndUnzipTc tcFImport [ foreign_decl | ForD foreign_decl <- decls, isForeignImport foreign_decl]
66
67 tcForeignExports :: [RenamedHsDecl] -> TcM s (LIE, TcMonoBinds, [TcForeignExportDecl])
68 tcForeignExports decls = 
69    foldlTc combine (emptyLIE, EmptyMonoBinds, [])
70                    [ foreign_decl | ForD foreign_decl <- decls, isForeignExport foreign_decl]
71   where
72    combine (lie, binds, fs) fe = 
73        tcFExport fe `thenTc ` \ (a_lie, b, f) ->
74        returnTc (lie `plusLIE` a_lie, b `AndMonoBinds` binds, f:fs)
75
76 -- defines a binding
77 isForeignImport :: ForeignDecl name -> Bool
78 isForeignImport (ForeignDecl _ k _ dyn _ _) =
79   case k of
80     FoImport _ -> True
81     FoExport   -> case dyn of { Dynamic -> True ; _ -> False }
82     FoLabel    -> True
83
84 -- exports a binding
85 isForeignExport :: ForeignDecl name -> Bool
86 isForeignExport (ForeignDecl _ FoExport _ ext_nm _ _) = not (isDynamicExtName ext_nm)
87 isForeignExport _                                     = False
88
89 \end{code}
90
91 \begin{code}
92 tcFImport :: RenamedForeignDecl -> TcM s (Id, TypecheckedForeignDecl)
93 tcFImport fo@(ForeignDecl nm FoExport hs_ty Dynamic cconv src_loc) =
94    tcAddSrcLoc src_loc               $
95    tcAddErrCtxt (foreignDeclCtxt fo) $
96    tcHsTopBoxedType hs_ty            `thenTc`   \ sig_ty ->
97    let
98       -- drop the foralls before inspecting the structure
99       -- of the foreign type.
100     (_, t_ty) = splitForAllTys sig_ty
101    in
102    case splitFunTys t_ty of
103      (arg_tys, res_ty) -> 
104         checkForeignExport True t_ty arg_tys res_ty `thenTc_`
105         let i = (mkVanillaId nm sig_ty) in
106         returnTc (i, (ForeignDecl i FoExport undefined Dynamic cconv src_loc))
107
108 tcFImport fo@(ForeignDecl nm FoLabel hs_ty ext_nm cconv src_loc) =
109    tcAddSrcLoc src_loc               $
110    tcAddErrCtxt (foreignDeclCtxt fo) $
111    tcHsTopBoxedType hs_ty           `thenTc`    \ sig_ty ->
112    let
113       -- drop the foralls before inspecting the structure
114       -- of the foreign type.
115     (_, t_ty) = splitForAllTys sig_ty
116    in
117    check (isAddrTy t_ty) (illegalForeignTyErr False{-result-} sig_ty) `thenTc_`
118    let i = (mkVanillaId nm sig_ty) in
119    returnTc (i, (ForeignDecl i FoLabel undefined ext_nm cconv src_loc))
120
121 tcFImport fo@(ForeignDecl nm imp_exp@(FoImport isUnsafe) hs_ty ext_nm cconv src_loc) =
122    tcAddSrcLoc src_loc               $
123    tcAddErrCtxt (foreignDeclCtxt fo) $
124
125    tcHsTopBoxedType hs_ty            `thenTc` \ ty ->
126     -- Check that the type has the right shape
127     -- and that the argument and result types are acceptable.
128    let
129       -- drop the foralls before inspecting the structure
130       -- of the foreign type.
131     (_, t_ty) = splitForAllTys ty
132    in
133    case splitFunTys t_ty of
134      (arg_tys, res_ty) ->
135         checkForeignImport (isDynamicExtName ext_nm) (not isUnsafe) ty arg_tys res_ty `thenTc_`
136         let i = (mkVanillaId nm ty) in
137         returnTc (i, (ForeignDecl i imp_exp undefined ext_nm cconv src_loc))
138
139 tcFExport :: RenamedForeignDecl -> TcM s (LIE, TcMonoBinds, TcForeignExportDecl)
140 tcFExport fo@(ForeignDecl nm imp_exp hs_ty ext_nm cconv src_loc) =
141    tcAddSrcLoc src_loc               $
142    tcAddErrCtxt (foreignDeclCtxt fo) $
143
144    tcHsTopBoxedType hs_ty              `thenTc` \ sig_ty ->
145    let sig_tc_ty = typeToTcType sig_ty in
146    tcPolyExpr (HsVar nm) sig_tc_ty     `thenTc`    \ (rhs, lie, _, _, _) ->
147
148    let
149       -- drop the foralls before inspecting the structure
150       -- of the foreign type.
151     (_, t_ty) = splitForAllTys sig_ty
152    in
153    case splitFunTys t_ty of
154      (arg_tys, res_ty) -> 
155         checkForeignExport False t_ty arg_tys res_ty `thenTc_`
156           -- we're exporting a function, but at a type possibly more constrained
157           -- than its declared/inferred type. Hence the need
158           -- to create a local binding which will call the exported function
159           -- at a particular type (and, maybe, overloading).
160         newLocalId (nameOccName nm) sig_tc_ty src_loc   `thenNF_Tc` \ i ->
161         let
162             bind  = VarMonoBind i rhs
163         in
164         returnTc (lie, bind, ForeignDecl i 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 -> Bool -> Type -> [Type] -> Type -> TcM s ()
173 checkForeignImport is_dynamic is_safe 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 is_safe)) xs    `thenTc_`
181         checkForeignRes (isFFIResultTy) res
182  | otherwise =
183      mapTc (checkForeignArg (isFFIArgumentTy is_safe)) 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}