[project @ 2001-06-25 08:09:57 by simonpj]
[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                           MonoBinds(..), FoImport(..), FoExport(..)
24                         )
25 import RnHsSyn          ( RenamedHsDecl, RenamedForeignDecl )
26
27 import TcMonad
28 import TcEnv            ( newLocalId )
29 import TcMonoType       ( tcHsLiftedSigType )
30 import TcHsSyn          ( TcMonoBinds, TypecheckedForeignDecl,
31                           TcForeignExportDecl )
32 import TcExpr           ( tcPolyExpr )                  
33 import Inst             ( emptyLIE, LIE, plusLIE )
34
35 import ErrUtils         ( Message )
36 import Id               ( Id, mkLocalId )
37 import Name             ( nameOccName )
38 import TysWiredIn       ( isFFIArgumentTy, isFFIImportResultTy, 
39                           isFFIExportResultTy,
40                           isFFIExternalTy, isFFIDynArgumentTy, isFFIDynResultTy,
41                           isFFILabelTy
42                         )
43 import TcType           ( Type, tcSplitFunTys, tcSplitTyConApp_maybe, tcSplitForAllTys )
44 import ForeignCall      ( CCallSpec(..), CExportSpec(..), CCallTarget(..), isDynamicTarget, isCasmTarget )
45 import CStrings         ( CLabelString, isCLabelString )
46 import PrelNames        ( hasKey, ioTyConKey )
47 import CmdLineOpts      ( dopt_HscLang, HscLang(..) )
48 import Outputable
49
50 \end{code}
51
52 \begin{code}
53 -- Defines a binding
54 isForeignImport :: ForeignDecl name -> Bool
55 isForeignImport (ForeignImport _ _ _ _) = True
56 isForeignImport _                       = False
57
58 -- Exports a binding
59 isForeignExport :: ForeignDecl name -> Bool
60 isForeignExport (ForeignExport _ _ _ _) = True
61 isForeignExport _                       = False
62 \end{code}
63
64 %************************************************************************
65 %*                                                                      *
66 \subsection{Imports}
67 %*                                                                      *
68 %************************************************************************
69
70 \begin{code}
71 tcForeignImports :: [RenamedHsDecl] -> TcM ([Id], [TypecheckedForeignDecl])
72 tcForeignImports decls = 
73    mapAndUnzipTc tcFImport [ foreign_decl | ForD foreign_decl <- decls, isForeignImport foreign_decl]
74
75 tcFImport :: RenamedForeignDecl -> TcM (Id, TypecheckedForeignDecl)
76 tcFImport fo@(ForeignImport nm hs_ty imp_decl src_loc)
77  = tcAddSrcLoc src_loc                  $
78    tcAddErrCtxt (foreignDeclCtxt fo)    $
79    tcHsLiftedSigType hs_ty              `thenTc`        \ sig_ty ->
80    let 
81       -- drop the foralls before inspecting the structure
82       -- of the foreign type.
83         (_, t_ty)         = tcSplitForAllTys sig_ty
84         (arg_tys, res_ty) = tcSplitFunTys t_ty
85         id                = mkLocalId nm sig_ty
86    in
87    tcCheckFIType sig_ty arg_tys res_ty imp_decl         `thenNF_Tc_` 
88    returnTc (id, ForeignImport id undefined imp_decl src_loc)
89 \end{code}
90
91
92 ------------ Checking types for foreign import ----------------------
93 \begin{code}
94 tcCheckFIType _ _ _ (DNImport _)
95   = checkCg checkDotNet
96
97 tcCheckFIType sig_ty arg_tys res_ty (LblImport _)
98   = checkCg checkCOrAsm         `thenNF_Tc_`
99     check (isFFILabelTy sig_ty) (illegalForeignTyErr empty sig_ty)
100
101 tcCheckFIType sig_ty arg_tys res_ty (CDynImport _)
102   =     -- Foreign export dynamic
103         -- The first (and only!) arg has got to be a function type
104         -- and it must return IO t; result type is IO Addr
105     checkCg checkCOrAsm         `thenNF_Tc_`
106     case arg_tys of
107         [arg1_ty] -> checkForeignArgs isFFIExternalTy arg1_tys                  `thenNF_Tc_`
108                      checkForeignRes nonIOok  isFFIExportResultTy res1_ty       `thenNF_Tc_`
109                      checkForeignRes mustBeIO isFFIDynResultTy    res_ty
110                   where
111                      (arg1_tys, res1_ty) = tcSplitFunTys arg1_ty
112         other -> addErrTc (illegalForeignTyErr empty sig_ty)
113
114 tcCheckFIType sig_ty arg_tys res_ty (CImport (CCallSpec target _ safety))
115   | isDynamicTarget target      -- Foreign import dynamic
116   = checkCg checkCOrAsm         `thenNF_Tc_`
117     case arg_tys of             -- The first arg must be Addr
118       []                -> check False (illegalForeignTyErr empty sig_ty)
119       (arg1_ty:arg_tys) -> getDOptsTc                                                   `thenNF_Tc` \ dflags ->
120                            check (isFFIDynArgumentTy arg1_ty)
121                                  (illegalForeignTyErr argument arg1_ty)                 `thenNF_Tc_`
122                            checkForeignArgs (isFFIArgumentTy dflags safety) arg_tys     `thenNF_Tc_`
123                            checkForeignRes nonIOok (isFFIImportResultTy dflags) res_ty
124
125   | otherwise           -- Normal foreign import
126   = checkCg (if isCasmTarget target
127              then checkC else checkCOrAsmOrDotNet)                      `thenNF_Tc_`
128     checkCTarget target                                         `thenNF_Tc_`
129     getDOptsTc                                                  `thenNF_Tc` \ dflags ->
130     checkForeignArgs (isFFIArgumentTy dflags safety) arg_tys    `thenNF_Tc_`
131     checkForeignRes nonIOok (isFFIImportResultTy dflags) res_ty
132
133 -- This makes a convenient place to check
134 -- that the C identifier is valid for C
135 checkCTarget (StaticTarget str) 
136   = checkCg checkCOrAsmOrDotNet         `thenNF_Tc_`
137     check (isCLabelString str) (badCName str)
138
139 checkCTarget (CasmTarget _)
140   = checkCg checkC
141 \end{code}
142
143
144 %************************************************************************
145 %*                                                                      *
146 \subsection{Exports}
147 %*                                                                      *
148 %************************************************************************
149
150 \begin{code}
151 tcForeignExports :: [RenamedHsDecl] -> TcM (LIE, TcMonoBinds, [TcForeignExportDecl])
152 tcForeignExports decls = 
153    foldlTc combine (emptyLIE, EmptyMonoBinds, [])
154                    [ foreign_decl | ForD foreign_decl <- decls, isForeignExport foreign_decl]
155   where
156    combine (lie, binds, fs) fe = 
157        tcFExport fe `thenTc ` \ (a_lie, b, f) ->
158        returnTc (lie `plusLIE` a_lie, b `AndMonoBinds` binds, f:fs)
159
160 tcFExport :: RenamedForeignDecl -> TcM (LIE, TcMonoBinds, TcForeignExportDecl)
161 tcFExport fo@(ForeignExport nm hs_ty spec src_loc) =
162    tcAddSrcLoc src_loc                  $
163    tcAddErrCtxt (foreignDeclCtxt fo)    $
164
165    tcHsLiftedSigType hs_ty             `thenTc` \ sig_ty ->
166    tcPolyExpr (HsVar nm) sig_ty         `thenTc`    \ (rhs, lie, _, _, _) ->
167
168    tcCheckFEType sig_ty spec            `thenTc_`
169
170           -- we're exporting a function, but at a type possibly more constrained
171           -- than its declared/inferred type. Hence the need
172           -- to create a local binding which will call the exported function
173           -- at a particular type (and, maybe, overloading).
174    newLocalId (nameOccName nm) sig_ty src_loc   `thenNF_Tc` \ id ->
175    let
176         bind  = VarMonoBind id rhs
177    in
178    returnTc (lie, bind, ForeignExport id undefined spec src_loc)
179 \end{code}
180
181 ------------ Checking argument types for foreign export ----------------------
182
183 \begin{code}
184 tcCheckFEType sig_ty (CExport (CExportStatic str _))
185   = check (isCLabelString str) (badCName str)           `thenNF_Tc_`
186     checkForeignArgs isFFIExternalTy arg_tys            `thenNF_Tc_`
187     checkForeignRes nonIOok isFFIExportResultTy res_ty
188   where
189       -- Drop the foralls before inspecting n
190       -- the structure of the foreign type.
191     (_, t_ty) = tcSplitForAllTys sig_ty
192     (arg_tys, res_ty) = tcSplitFunTys t_ty
193 \end{code}
194
195
196
197 %************************************************************************
198 %*                                                                      *
199 \subsection{Miscellaneous}
200 %*                                                                      *
201 %************************************************************************
202
203 \begin{code}
204 ------------ Checking argument types for foreign import ----------------------
205 checkForeignArgs :: (Type -> Bool) -> [Type] -> NF_TcM ()
206 checkForeignArgs pred tys
207   = mapNF_Tc go tys     `thenNF_Tc_` returnNF_Tc ()
208   where
209     go ty = check (pred ty) (illegalForeignTyErr argument ty)
210
211
212 ------------ Checking result types for foreign calls ----------------------
213 -- Check that the type has the form 
214 --    (IO t) or (t) , and that t satisfies the given predicate.
215 --
216 checkForeignRes :: Bool -> (Type -> Bool) -> Type -> NF_TcM ()
217
218 nonIOok  = True
219 mustBeIO = False
220
221 checkForeignRes non_io_result_ok pred_res_ty ty
222  = case tcSplitTyConApp_maybe ty of
223       Just (io, [res_ty]) 
224         | io `hasKey` ioTyConKey && pred_res_ty res_ty 
225         -> returnNF_Tc ()
226       _   
227         -> check (non_io_result_ok && pred_res_ty ty) 
228                  (illegalForeignTyErr result ty)
229 \end{code}
230
231 \begin{code} 
232 checkDotNet HscILX = Nothing
233 checkDotNet other  = Just (text "requires .NET code generation (-filx)")
234
235 checkC HscC  = Nothing
236 checkC other = Just (text "requires C code generation (-fvia-C)")
237                            
238 checkCOrAsm HscC   = Nothing
239 checkCOrAsm HscAsm = Nothing
240 checkCOrAsm other  = Just (text "via-C or native code generation (-fvia-C)")
241
242 checkCOrAsmOrDotNet HscC   = Nothing
243 checkCOrAsmOrDotNet HscAsm = Nothing
244 checkCOrAsmOrDotNet HscILX = Nothing
245 checkCOrAsmOrDotNet other  = Just (text "requires C, native or .NET ILX code generation")
246
247 checkCg check
248  = getDOptsTc           `thenNF_Tc` \ dflags ->
249    case check (dopt_HscLang dflags) of
250         Nothing  -> returnNF_Tc ()
251         Just err -> addErrTc (text "Illegal foreign declaration:" <+> err)
252 \end{code} 
253                            
254 Warnings
255
256 \begin{code}
257 check :: Bool -> Message -> NF_TcM ()
258 check True _       = returnTc ()
259 check _    the_err = addErrTc the_err
260
261 illegalForeignTyErr arg_or_res ty
262   = hang (hsep [ptext SLIT("Unacceptable"), arg_or_res, ptext SLIT("type in foreign declaration:")])
263          4 (hsep [ppr ty])
264
265 -- Used for 'arg_or_res' argument to illegalForeignTyErr
266 argument = text "argument"
267 result   = text "result"
268
269 badCName :: CLabelString -> Message
270 badCName target = sep [quotes (ppr target) <+> ptext SLIT("is not a valid C identifier")]
271
272 foreignDeclCtxt fo
273   = hang (ptext SLIT("When checking declaration:"))
274      4   (ppr fo)
275 \end{code}