[project @ 2001-09-04 18:22:34 by ken]
[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 On an Alpha, due to a similar hack, we only allow 4 integer arguments with
151 foreign export dynamic (i.e., 32 bytes of arguments after padding each
152 argument to a quadword, excluding floating-point arguments).
153
154 The check is needed for both via-C and native-code routes
155
156 \begin{code}
157 #include "nativeGen/NCG.h"
158 #if sparc_TARGET_ARCH
159 checkFEDArgs arg_tys
160   = check (words_of_args <= 4) err
161   where
162     words_of_args = sum (map (getPrimRepSize . typePrimRep) arg_tys)
163     err = ptext SLIT("On SPARC, I can only handle 4 words of arguments to foreign export dynamic")
164 #elsif alpha_TARGET_ARCH
165 checkFEDArgs arg_tys
166   = check (integral_args <= 4) err
167   where
168     integral_args = sum (map (getPrimRepSize . filter (not . isFloatingRep)
169                                              . typePrimRep) arg_tys)
170     err = ptext SLIT("On Alpha, I can only handle 4 non-floating-point arguments to foreign export dynamic")
171 #else
172 checkFEDArgs arg_tys = returnNF_Tc ()
173 #endif
174 \end{code}
175
176
177 %************************************************************************
178 %*                                                                      *
179 \subsection{Exports}
180 %*                                                                      *
181 %************************************************************************
182
183 \begin{code}
184 tcForeignExports :: [RenamedHsDecl] -> TcM (LIE, TcMonoBinds, [TcForeignExportDecl])
185 tcForeignExports decls = 
186    foldlTc combine (emptyLIE, EmptyMonoBinds, [])
187                    [ foreign_decl | ForD foreign_decl <- decls, isForeignExport foreign_decl]
188   where
189    combine (lie, binds, fs) fe = 
190        tcFExport fe `thenTc ` \ (a_lie, b, f) ->
191        returnTc (lie `plusLIE` a_lie, b `AndMonoBinds` binds, f:fs)
192
193 tcFExport :: RenamedForeignDecl -> TcM (LIE, TcMonoBinds, TcForeignExportDecl)
194 tcFExport fo@(ForeignExport nm hs_ty spec src_loc) =
195    tcAddSrcLoc src_loc                  $
196    tcAddErrCtxt (foreignDeclCtxt fo)    $
197
198    tcHsSigType (ForSigCtxt nm) hs_ty    `thenTc` \ sig_ty ->
199    tcPolyExpr (HsVar nm) sig_ty         `thenTc` \ (rhs, lie, _, _, _) ->
200
201    tcCheckFEType sig_ty spec            `thenTc_`
202
203           -- we're exporting a function, but at a type possibly more constrained
204           -- than its declared/inferred type. Hence the need
205           -- to create a local binding which will call the exported function
206           -- at a particular type (and, maybe, overloading).
207    newLocalId (nameOccName nm) sig_ty src_loc   `thenNF_Tc` \ id ->
208    let
209         bind  = VarMonoBind id rhs
210    in
211    returnTc (lie, bind, ForeignExport id undefined spec src_loc)
212 \end{code}
213
214 ------------ Checking argument types for foreign export ----------------------
215
216 \begin{code}
217 tcCheckFEType sig_ty (CExport (CExportStatic str _))
218   = check (isCLabelString str) (badCName str)           `thenNF_Tc_`
219     checkForeignArgs isFFIExternalTy arg_tys            `thenNF_Tc_`
220     checkForeignRes nonIOok isFFIExportResultTy res_ty
221   where
222       -- Drop the foralls before inspecting n
223       -- the structure of the foreign type.
224     (_, t_ty) = tcSplitForAllTys sig_ty
225     (arg_tys, res_ty) = tcSplitFunTys t_ty
226 \end{code}
227
228
229
230 %************************************************************************
231 %*                                                                      *
232 \subsection{Miscellaneous}
233 %*                                                                      *
234 %************************************************************************
235
236 \begin{code}
237 ------------ Checking argument types for foreign import ----------------------
238 checkForeignArgs :: (Type -> Bool) -> [Type] -> NF_TcM ()
239 checkForeignArgs pred tys
240   = mapNF_Tc go tys     `thenNF_Tc_` returnNF_Tc ()
241   where
242     go ty = check (pred ty) (illegalForeignTyErr argument ty)
243
244
245 ------------ Checking result types for foreign calls ----------------------
246 -- Check that the type has the form 
247 --    (IO t) or (t) , and that t satisfies the given predicate.
248 --
249 checkForeignRes :: Bool -> (Type -> Bool) -> Type -> NF_TcM ()
250
251 nonIOok  = True
252 mustBeIO = False
253
254 checkForeignRes non_io_result_ok pred_res_ty ty
255  = case tcSplitTyConApp_maybe ty of
256       Just (io, [res_ty]) 
257         | io `hasKey` ioTyConKey && pred_res_ty res_ty 
258         -> returnNF_Tc ()
259       _   
260         -> check (non_io_result_ok && pred_res_ty ty) 
261                  (illegalForeignTyErr result ty)
262 \end{code}
263
264 \begin{code} 
265 checkDotNet HscILX = Nothing
266 checkDotNet other  = Just (text "requires .NET code generation (-filx)")
267
268 checkC HscC  = Nothing
269 checkC other = Just (text "requires C code generation (-fvia-C)")
270                            
271 checkCOrAsm HscC   = Nothing
272 checkCOrAsm HscAsm = Nothing
273 checkCOrAsm other  
274    = Just (text "requires via-C or native code generation (-fvia-C)")
275
276 checkCOrAsmOrInterp HscC           = Nothing
277 checkCOrAsmOrInterp HscAsm         = Nothing
278 checkCOrAsmOrInterp HscInterpreted = Nothing
279 checkCOrAsmOrInterp other  
280    = Just (text "requires interpreted, C or native code generation")
281
282 checkCOrAsmOrDotNet HscC   = Nothing
283 checkCOrAsmOrDotNet HscAsm = Nothing
284 checkCOrAsmOrDotNet HscILX = Nothing
285 checkCOrAsmOrDotNet other  
286    = Just (text "requires C, native or .NET ILX code generation")
287
288 checkCOrAsmOrDotNetOrInterp HscC           = Nothing
289 checkCOrAsmOrDotNetOrInterp HscAsm         = Nothing
290 checkCOrAsmOrDotNetOrInterp HscILX         = Nothing
291 checkCOrAsmOrDotNetOrInterp HscInterpreted = Nothing
292 checkCOrAsmOrDotNetOrInterp other  
293    = Just (text "requires interpreted, C, native or .NET ILX code generation")
294
295 checkCg check
296  = getDOptsTc           `thenNF_Tc` \ dflags ->
297    let hscLang = dopt_HscLang dflags in
298    case hscLang of
299         HscNothing -> returnNF_Tc ()
300         otherwise ->
301           case check hscLang of
302                Nothing  -> returnNF_Tc ()
303                Just err -> addErrTc (text "Illegal foreign declaration:" <+> err)
304 \end{code} 
305                            
306 Warnings
307
308 \begin{code}
309 check :: Bool -> Message -> NF_TcM ()
310 check True _       = returnTc ()
311 check _    the_err = addErrTc the_err
312
313 illegalForeignTyErr arg_or_res ty
314   = hang (hsep [ptext SLIT("Unacceptable"), arg_or_res, 
315                 ptext SLIT("type in foreign declaration:")])
316          4 (hsep [ppr ty])
317
318 -- Used for 'arg_or_res' argument to illegalForeignTyErr
319 argument = text "argument"
320 result   = text "result"
321
322 badCName :: CLabelString -> Message
323 badCName target 
324    = sep [quotes (ppr target) <+> ptext SLIT("is not a valid C identifier")]
325
326 foreignDeclCtxt fo
327   = hang (ptext SLIT("When checking declaration:"))
328          4 (ppr fo)
329 \end{code}
330