c33b8cdfc003acc9e11dd00c500f339af876a776
[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       ( tcHsSigType, UserTypeCtxt(..) )
30 import TcHsSyn          ( TcMonoBinds, TypecheckedForeignDecl, TcForeignExportDecl )
31 import TcExpr           ( tcPolyExpr )                  
32 import Inst             ( emptyLIE, LIE, plusLIE )
33
34 import ErrUtils         ( Message )
35 import Id               ( Id, mkLocalId )
36 import Name             ( nameOccName )
37 import PrimRep          ( getPrimRepSize )
38 import Type             ( typePrimRep )
39 import TcType           ( Type, tcSplitFunTys, tcSplitTyConApp_maybe, tcSplitForAllTys,
40                           isFFIArgumentTy, isFFIImportResultTy, 
41                           isFFIExportResultTy, isFFILabelTy,
42                           isFFIExternalTy, isFFIDynArgumentTy, isFFIDynResultTy
43                         )
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    tcHsSigType (ForSigCtxt nm) 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        `thenNF_Tc_`
110                      checkFEDArgs arg1_tys
111                   where
112                      (arg1_tys, res1_ty) = tcSplitFunTys arg1_ty
113         other -> addErrTc (illegalForeignTyErr empty sig_ty)
114
115 tcCheckFIType sig_ty arg_tys res_ty (CImport (CCallSpec target _ safety))
116   | isDynamicTarget target      -- Foreign import dynamic
117   = checkCg checkCOrAsmOrInterp         `thenNF_Tc_`
118     case arg_tys of             -- The first arg must be Addr
119       []                -> check False (illegalForeignTyErr empty sig_ty)
120       (arg1_ty:arg_tys) -> getDOptsTc                                                   `thenNF_Tc` \ dflags ->
121                            check (isFFIDynArgumentTy arg1_ty)
122                                  (illegalForeignTyErr argument arg1_ty)                 `thenNF_Tc_`
123                            checkForeignArgs (isFFIArgumentTy dflags safety) arg_tys     `thenNF_Tc_`
124                            checkForeignRes nonIOok (isFFIImportResultTy dflags) res_ty
125
126   | otherwise           -- Normal foreign import
127   = checkCg (if isCasmTarget target
128              then checkC else checkCOrAsmOrDotNetOrInterp)      `thenNF_Tc_`
129     checkCTarget target                                         `thenNF_Tc_`
130     getDOptsTc                                                  `thenNF_Tc` \ dflags ->
131     checkForeignArgs (isFFIArgumentTy dflags safety) arg_tys    `thenNF_Tc_`
132     checkForeignRes nonIOok (isFFIImportResultTy dflags) res_ty
133
134 -- This makes a convenient place to check
135 -- that the C identifier is valid for C
136 checkCTarget (StaticTarget str) 
137   = checkCg checkCOrAsmOrDotNetOrInterp         `thenNF_Tc_`
138     check (isCLabelString str) (badCName str)
139
140 checkCTarget (CasmTarget _)
141   = checkCg checkC
142 \end{code}
143
144 On a SPARC, with foreign export dynamic, due to a giant hack when building
145 adjustor thunks, we only allow 16 bytes of arguments!
146
147 So for example, args (Int,Double,Int) would be OK (1+2+1)
148 as would (Int,Int,Int,Int) (1+1+1+1) but not (Int,Double,Double) (1+2+2).
149
150 The check is needed for both via-C and native-code routes
151
152 \begin{code}
153 #include "nativeGen/NCG.h"
154 #if sparc_TARGET_ARCH
155 checkFEDArgs arg_tys
156   = check (words_of_args <= 4) err
157   where
158     words_of_args = sum (map (getPrimRepSize . typePrimRep) arg_tys)
159     err = ptext SLIT("On SPARC, I can only handle 4 words of arguments to foreign export dynamic")
160 #else
161 checkFEDArgs arg_tys = returnNF_Tc ()
162 #endif
163 \end{code}
164
165
166 %************************************************************************
167 %*                                                                      *
168 \subsection{Exports}
169 %*                                                                      *
170 %************************************************************************
171
172 \begin{code}
173 tcForeignExports :: [RenamedHsDecl] -> TcM (LIE, TcMonoBinds, [TcForeignExportDecl])
174 tcForeignExports decls = 
175    foldlTc combine (emptyLIE, EmptyMonoBinds, [])
176                    [ foreign_decl | ForD foreign_decl <- decls, isForeignExport foreign_decl]
177   where
178    combine (lie, binds, fs) fe = 
179        tcFExport fe `thenTc ` \ (a_lie, b, f) ->
180        returnTc (lie `plusLIE` a_lie, b `AndMonoBinds` binds, f:fs)
181
182 tcFExport :: RenamedForeignDecl -> TcM (LIE, TcMonoBinds, TcForeignExportDecl)
183 tcFExport fo@(ForeignExport nm hs_ty spec src_loc) =
184    tcAddSrcLoc src_loc                  $
185    tcAddErrCtxt (foreignDeclCtxt fo)    $
186
187    tcHsSigType (ForSigCtxt nm) hs_ty    `thenTc` \ sig_ty ->
188    tcPolyExpr (HsVar nm) sig_ty         `thenTc` \ (rhs, lie, _, _, _) ->
189
190    tcCheckFEType sig_ty spec            `thenTc_`
191
192           -- we're exporting a function, but at a type possibly more constrained
193           -- than its declared/inferred type. Hence the need
194           -- to create a local binding which will call the exported function
195           -- at a particular type (and, maybe, overloading).
196    newLocalId (nameOccName nm) sig_ty src_loc   `thenNF_Tc` \ id ->
197    let
198         bind  = VarMonoBind id rhs
199    in
200    returnTc (lie, bind, ForeignExport id undefined spec src_loc)
201 \end{code}
202
203 ------------ Checking argument types for foreign export ----------------------
204
205 \begin{code}
206 tcCheckFEType sig_ty (CExport (CExportStatic str _))
207   = check (isCLabelString str) (badCName str)           `thenNF_Tc_`
208     checkForeignArgs isFFIExternalTy arg_tys            `thenNF_Tc_`
209     checkForeignRes nonIOok isFFIExportResultTy res_ty
210   where
211       -- Drop the foralls before inspecting n
212       -- the structure of the foreign type.
213     (_, t_ty) = tcSplitForAllTys sig_ty
214     (arg_tys, res_ty) = tcSplitFunTys t_ty
215 \end{code}
216
217
218
219 %************************************************************************
220 %*                                                                      *
221 \subsection{Miscellaneous}
222 %*                                                                      *
223 %************************************************************************
224
225 \begin{code}
226 ------------ Checking argument types for foreign import ----------------------
227 checkForeignArgs :: (Type -> Bool) -> [Type] -> NF_TcM ()
228 checkForeignArgs pred tys
229   = mapNF_Tc go tys     `thenNF_Tc_` returnNF_Tc ()
230   where
231     go ty = check (pred ty) (illegalForeignTyErr argument ty)
232
233
234 ------------ Checking result types for foreign calls ----------------------
235 -- Check that the type has the form 
236 --    (IO t) or (t) , and that t satisfies the given predicate.
237 --
238 checkForeignRes :: Bool -> (Type -> Bool) -> Type -> NF_TcM ()
239
240 nonIOok  = True
241 mustBeIO = False
242
243 checkForeignRes non_io_result_ok pred_res_ty ty
244  = case tcSplitTyConApp_maybe ty of
245       Just (io, [res_ty]) 
246         | io `hasKey` ioTyConKey && pred_res_ty res_ty 
247         -> returnNF_Tc ()
248       _   
249         -> check (non_io_result_ok && pred_res_ty ty) 
250                  (illegalForeignTyErr result ty)
251 \end{code}
252
253 \begin{code} 
254 checkDotNet HscILX = Nothing
255 checkDotNet other  = Just (text "requires .NET code generation (-filx)")
256
257 checkC HscC  = Nothing
258 checkC other = Just (text "requires C code generation (-fvia-C)")
259                            
260 checkCOrAsm HscC   = Nothing
261 checkCOrAsm HscAsm = Nothing
262 checkCOrAsm other  
263    = Just (text "requires via-C or native code generation (-fvia-C)")
264
265 checkCOrAsmOrInterp HscC           = Nothing
266 checkCOrAsmOrInterp HscAsm         = Nothing
267 checkCOrAsmOrInterp HscInterpreted = Nothing
268 checkCOrAsmOrInterp other  
269    = Just (text "requires interpreted, C or native code generation")
270
271 checkCOrAsmOrDotNet HscC   = Nothing
272 checkCOrAsmOrDotNet HscAsm = Nothing
273 checkCOrAsmOrDotNet HscILX = Nothing
274 checkCOrAsmOrDotNet other  
275    = Just (text "requires C, native or .NET ILX code generation")
276
277 checkCOrAsmOrDotNetOrInterp HscC           = Nothing
278 checkCOrAsmOrDotNetOrInterp HscAsm         = Nothing
279 checkCOrAsmOrDotNetOrInterp HscILX         = Nothing
280 checkCOrAsmOrDotNetOrInterp HscInterpreted = Nothing
281 checkCOrAsmOrDotNetOrInterp other  
282    = Just (text "requires interpreted, C, native or .NET ILX code generation")
283
284 checkCg check
285  = getDOptsTc           `thenNF_Tc` \ dflags ->
286    let hscLang = dopt_HscLang dflags in
287    case hscLang of
288         HscNothing -> returnNF_Tc ()
289         otherwise ->
290           case check hscLang of
291                Nothing  -> returnNF_Tc ()
292                Just err -> addErrTc (text "Illegal foreign declaration:" <+> err)
293 \end{code} 
294                            
295 Warnings
296
297 \begin{code}
298 check :: Bool -> Message -> NF_TcM ()
299 check True _       = returnTc ()
300 check _    the_err = addErrTc the_err
301
302 illegalForeignTyErr arg_or_res ty
303   = hang (hsep [ptext SLIT("Unacceptable"), arg_or_res, 
304                 ptext SLIT("type in foreign declaration:")])
305          4 (hsep [ppr ty])
306
307 -- Used for 'arg_or_res' argument to illegalForeignTyErr
308 argument = text "argument"
309 result   = text "result"
310
311 badCName :: CLabelString -> Message
312 badCName target 
313    = sep [quotes (ppr target) <+> ptext SLIT("is not a valid C identifier")]
314
315 foreignDeclCtxt fo
316   = hang (ptext SLIT("When checking declaration:"))
317          4 (ppr fo)
318 \end{code}
319