[project @ 2000-05-13 00:20:57 by lewie]
[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                         )
45 import PprType          ( {- instance Outputable Type -} )
46 import TysWiredIn       ( isFFIArgumentTy, isFFIResultTy, 
47                           isFFIExternalTy, isAddrTy
48                         )
49 import Type             ( Type )
50 import Unique
51 import Outputable
52 import Util
53 import CmdLineOpts      ( opt_GlasgowExts )
54 import Maybes           ( maybeToBool )
55
56 \end{code}
57
58 \begin{code}
59 tcForeignImports :: [RenamedHsDecl] -> TcM s ([Id], [TypecheckedForeignDecl])
60 tcForeignImports decls = 
61    mapAndUnzipTc tcFImport [ foreign_decl | ForD foreign_decl <- decls, isForeignImport foreign_decl]
62
63 tcForeignExports :: [RenamedHsDecl] -> TcM s (LIE, TcMonoBinds, [TcForeignExportDecl])
64 tcForeignExports decls = 
65    foldlTc combine (emptyLIE, EmptyMonoBinds, [])
66                    [ foreign_decl | ForD foreign_decl <- decls, isForeignExport foreign_decl]
67   where
68    combine (lie, binds, fs) fe = 
69        tcFExport fe `thenTc ` \ (a_lie, b, f) ->
70        returnTc (lie `plusLIE` a_lie, b `AndMonoBinds` binds, f:fs)
71
72 -- defines a binding
73 isForeignImport :: ForeignDecl name -> Bool
74 isForeignImport (ForeignDecl _ k _ dyn _ _) =
75   case k of
76     FoImport _ -> True
77     FoExport   -> case dyn of { Dynamic -> True ; _ -> False }
78     FoLabel    -> True
79
80 -- exports a binding
81 isForeignExport :: ForeignDecl name -> Bool
82 isForeignExport (ForeignDecl _ FoExport _ ext_nm _ _) = not (isDynamicExtName ext_nm)
83 isForeignExport _                                     = False
84
85 \end{code}
86
87 \begin{code}
88 tcFImport :: RenamedForeignDecl -> TcM s (Id, TypecheckedForeignDecl)
89 tcFImport fo@(ForeignDecl nm FoExport hs_ty Dynamic cconv src_loc) =
90    tcAddSrcLoc src_loc               $
91    tcAddErrCtxt (foreignDeclCtxt fo) $
92    tcHsTopBoxedType hs_ty            `thenTc`   \ sig_ty ->
93    let
94       -- drop the foralls before inspecting the structure
95       -- of the foreign type.
96     (_, t_ty) = splitForAllTys sig_ty
97    in
98    case splitFunTys t_ty of
99      (arg_tys, res_ty) -> 
100         checkForeignExport True t_ty arg_tys res_ty `thenTc_`
101         let i = (mkVanillaId nm sig_ty) in
102         returnTc (i, (ForeignDecl i FoExport undefined Dynamic cconv src_loc))
103
104 tcFImport fo@(ForeignDecl nm FoLabel hs_ty ext_nm cconv src_loc) =
105    tcAddSrcLoc src_loc               $
106    tcAddErrCtxt (foreignDeclCtxt fo) $
107    tcHsTopBoxedType hs_ty           `thenTc`    \ sig_ty ->
108    let
109       -- drop the foralls before inspecting the structure
110       -- of the foreign type.
111     (_, t_ty) = splitForAllTys sig_ty
112    in
113    check (isAddrTy t_ty) (illegalForeignTyErr False{-result-} sig_ty) `thenTc_`
114    let i = (mkVanillaId nm sig_ty) in
115    returnTc (i, (ForeignDecl i FoLabel undefined ext_nm cconv src_loc))
116
117 tcFImport fo@(ForeignDecl nm imp_exp@(FoImport isUnsafe) hs_ty ext_nm cconv src_loc) =
118    tcAddSrcLoc src_loc               $
119    tcAddErrCtxt (foreignDeclCtxt fo) $
120
121    tcHsTopBoxedType hs_ty            `thenTc` \ ty ->
122     -- Check that the type has the right shape
123     -- and that the argument and result types are acceptable.
124    let
125       -- drop the foralls before inspecting the structure
126       -- of the foreign type.
127     (_, t_ty) = splitForAllTys ty
128    in
129    case splitFunTys t_ty of
130      (arg_tys, res_ty) ->
131         checkForeignImport (isDynamicExtName ext_nm) (not isUnsafe) ty arg_tys res_ty `thenTc_`
132         let i = (mkVanillaId nm ty) in
133         returnTc (i, (ForeignDecl i imp_exp undefined ext_nm cconv src_loc))
134
135 tcFExport :: RenamedForeignDecl -> TcM s (LIE, TcMonoBinds, TcForeignExportDecl)
136 tcFExport fo@(ForeignDecl nm imp_exp hs_ty ext_nm cconv src_loc) =
137    tcAddSrcLoc src_loc               $
138    tcAddErrCtxt (foreignDeclCtxt fo) $
139
140    tcHsTopBoxedType hs_ty              `thenTc` \ sig_ty ->
141    let sig_tc_ty = typeToTcType sig_ty in
142    tcPolyExpr (HsVar nm) sig_tc_ty     `thenTc`    \ (rhs, lie, _, _, _) ->
143
144    let
145       -- drop the foralls before inspecting the structure
146       -- of the foreign type.
147     (_, t_ty) = splitForAllTys sig_ty
148    in
149    case splitFunTys t_ty of
150      (arg_tys, res_ty) -> 
151         checkForeignExport False t_ty arg_tys res_ty `thenTc_`
152           -- we're exporting a function, but at a type possibly more constrained
153           -- than its declared/inferred type. Hence the need
154           -- to create a local binding which will call the exported function
155           -- at a particular type (and, maybe, overloading).
156         newLocalId (nameOccName nm) sig_tc_ty src_loc   `thenNF_Tc` \ i ->
157         let
158             bind  = VarMonoBind i rhs
159         in
160         returnTc (lie, bind, ForeignDecl i imp_exp undefined ext_nm cconv src_loc)
161         --                                          ^^^^^^^^^
162         -- ToDo: fill the type field in with something sensible.
163
164 \end{code}
165
166
167 \begin{code}
168 checkForeignImport :: Bool -> Bool -> Type -> [Type] -> Type -> TcM s ()
169 checkForeignImport is_dynamic is_safe ty args res
170  | is_dynamic =
171     -- * first arg has got to be an Addr
172    case args of
173      []     -> check False (illegalForeignTyErr True{-Arg-} ty)
174      (x:xs) ->
175         check (isAddrTy x) (illegalForeignTyErr True{-Arg-} ty) `thenTc_`
176         mapTc (checkForeignArg (isFFIArgumentTy is_safe)) xs    `thenTc_`
177         checkForeignRes True {-NonIO ok-} isFFIResultTy res
178  | otherwise =
179      mapTc (checkForeignArg (isFFIArgumentTy is_safe)) args     `thenTc_`
180      checkForeignRes True {-NonIO ok-} isFFIResultTy res
181
182 checkForeignExport :: Bool -> Type -> [Type] -> Type -> TcM s ()
183 checkForeignExport is_dynamic ty args res
184  | is_dynamic = 
185     -- * the first (and only!) arg has got to be a function type
186     --   and it must return IO t
187     -- * result type is an Addr or IO Addr
188    case args of
189      [arg]  ->
190         case splitFunTys arg of
191            (arg_tys, res_ty) -> 
192                 mapTc (checkForeignArg isFFIExternalTy) arg_tys         `thenTc_`
193                 checkForeignRes True  {-NonIO ok-} isFFIResultTy res_ty `thenTc_`
194                 checkForeignRes False {-Must be IO-} isAddrTy      res
195      _      -> check False (illegalForeignTyErr True{-Arg-} ty)
196  | otherwise =
197      mapTc (checkForeignArg isFFIExternalTy) args               `thenTc_`
198      checkForeignRes True {-NonIO ok-} isFFIResultTy res
199  
200 checkForeignArg :: (Type -> Bool) -> Type -> TcM s ()
201 checkForeignArg pred ty = check (pred ty) (illegalForeignTyErr True{-Arg-} ty)
202
203 -- Check that the type has the form 
204 --    (IO t) or (t) , and that t satisfies the given predicate.
205 --
206 checkForeignRes :: Bool -> (Type -> Bool) -> Type -> TcM s ()
207 checkForeignRes non_io_result_ok pred_res_ty ty =
208  case (splitTyConApp_maybe ty) of
209     Just (io, [res_ty]) 
210         | (getUnique io) == ioTyConKey && pred_res_ty res_ty 
211         -> returnTc ()
212     _   
213         -> check (non_io_result_ok && pred_res_ty ty) 
214                  (illegalForeignTyErr False{-Res-} ty)
215 \end{code}
216
217 Warnings
218
219 \begin{code}
220 check :: Bool -> Message -> TcM s ()
221 check True _       = returnTc ()
222 check _    the_err = addErrTc the_err `thenNF_Tc_` returnTc ()
223
224 illegalForeignTyErr isArg ty
225   = hang (hsep [ptext SLIT("Unacceptable"), arg_or_res, ptext SLIT("type in foreign declaration:")])
226          4 (hsep [ppr ty])
227   where
228    arg_or_res
229     | isArg     = ptext SLIT("argument")
230     | otherwise = ptext SLIT("result")
231
232 foreignDeclCtxt fo = 
233  hang (ptext SLIT("When checking declaration:"))
234   4   (ppr fo)
235 \end{code}