[project @ 2002-02-28 12:17:19 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(..), ForeignImport(..), ForeignExport(..),
24                           CImportSpec(..)
25                         )
26 import RnHsSyn          ( RenamedHsDecl, RenamedForeignDecl )
27
28 import TcMonad
29 import TcMonoType       ( tcHsSigType, UserTypeCtxt(..) )
30 import TcHsSyn          ( TcMonoBinds, TypecheckedForeignDecl, TcForeignExportDecl )
31 import TcExpr           ( tcExpr )                      
32 import Inst             ( emptyLIE, LIE, plusLIE )
33
34 import ErrUtils         ( Message )
35 import Id               ( Id, mkLocalId, setIdLocalExported )
36 import PrimRep          ( getPrimRepSize, isFloatingRep )
37 import Module           ( Module )
38 import Type             ( typePrimRep )
39 import OccName          ( mkForeignExportOcc )
40 import Name             ( NamedThing(..), mkGlobalName )
41 import TcType           ( Type, tcSplitFunTys, tcSplitTyConApp_maybe,
42                           tcSplitForAllTys, 
43                           isFFIArgumentTy, isFFIImportResultTy, 
44                           isFFIExportResultTy, isFFILabelTy,
45                           isFFIExternalTy, isFFIDynArgumentTy,
46                           isFFIDynResultTy, isForeignPtrTy
47                         )
48 import ForeignCall      ( CExportSpec(..), CCallTarget(..),
49                           isDynamicTarget, isCasmTarget ) 
50 import CStrings         ( CLabelString, isCLabelString )
51 import PrelNames        ( hasKey, ioTyConKey )
52 import CmdLineOpts      ( dopt_HscLang, HscLang(..) )
53 import Outputable
54
55 \end{code}
56
57 \begin{code}
58 -- Defines a binding
59 isForeignImport :: ForeignDecl name -> Bool
60 isForeignImport (ForeignImport _ _ _ _ _) = True
61 isForeignImport _                         = False
62
63 -- Exports a binding
64 isForeignExport :: ForeignDecl name -> Bool
65 isForeignExport (ForeignExport _ _ _ _ _) = True
66 isForeignExport _                         = False
67 \end{code}
68
69 %************************************************************************
70 %*                                                                      *
71 \subsection{Imports}
72 %*                                                                      *
73 %************************************************************************
74
75 \begin{code}
76 tcForeignImports :: [RenamedHsDecl] -> TcM ([Id], [TypecheckedForeignDecl])
77 tcForeignImports decls = 
78   mapAndUnzipTc tcFImport 
79     [ foreign_decl | ForD foreign_decl <- decls, isForeignImport foreign_decl]
80
81 tcFImport :: RenamedForeignDecl -> TcM (Id, TypecheckedForeignDecl)
82 tcFImport fo@(ForeignImport nm hs_ty imp_decl isDeprec src_loc)
83  = tcAddSrcLoc src_loc                  $
84    tcAddErrCtxt (foreignDeclCtxt fo)    $
85    tcHsSigType (ForSigCtxt nm) hs_ty    `thenTc`        \ sig_ty ->
86    let 
87       -- drop the foralls before inspecting the structure
88       -- of the foreign type.
89         (_, t_ty)         = tcSplitForAllTys sig_ty
90         (arg_tys, res_ty) = tcSplitFunTys t_ty
91         id                = mkLocalId nm sig_ty
92    in
93    tcCheckFIType sig_ty arg_tys res_ty imp_decl         `thenNF_Tc_` 
94    -- can't use sig_ty here because it :: Type and we need HsType Id
95    -- hence the undefined
96    returnTc (id, ForeignImport id undefined imp_decl isDeprec src_loc)
97 \end{code}
98
99
100 ------------ Checking types for foreign import ----------------------
101 \begin{code}
102 tcCheckFIType _ _ _ (DNImport _)
103   = checkCg checkDotNet
104
105 tcCheckFIType sig_ty arg_tys res_ty (CImport _ _ _ _ (CLabel _))
106   = checkCg checkCOrAsm         `thenNF_Tc_`
107     check (isFFILabelTy sig_ty) (illegalForeignTyErr empty sig_ty)
108
109 tcCheckFIType sig_ty arg_tys res_ty (CImport _ _ _ _ CWrapper)
110   =     -- Foreign wrapper (former f.e.d.)
111         -- The type must be of the form ft -> IO (FunPtr ft), where ft is a
112         -- valid foreign type.  For legacy reasons ft -> IO (Ptr ft) as well
113         -- as ft -> IO Addr is accepted, too.  The use of the latter two forms
114         -- is DEPRECATED, though.
115     checkCg checkCOrAsmOrInterp         `thenNF_Tc_`
116     case arg_tys of
117         [arg1_ty] -> checkForeignArgs isFFIExternalTy arg1_tys                  `thenNF_Tc_`
118                      checkForeignRes nonIOok  isFFIExportResultTy res1_ty       `thenNF_Tc_`
119                      checkForeignRes mustBeIO isFFIDynResultTy    res_ty        `thenNF_Tc_`
120                      checkFEDArgs arg1_tys
121                   where
122                      (arg1_tys, res1_ty) = tcSplitFunTys arg1_ty
123         other -> addErrTc (illegalForeignTyErr empty sig_ty)
124
125 tcCheckFIType sig_ty arg_tys res_ty (CImport _ safety _ _ (CFunction target))
126   | isDynamicTarget target      -- Foreign import dynamic
127   = checkCg checkCOrAsmOrInterp         `thenNF_Tc_`
128     case arg_tys of             -- The first arg must be Ptr, FunPtr, or Addr
129       []                -> check False (illegalForeignTyErr empty sig_ty)
130       (arg1_ty:arg_tys) -> getDOptsTc                                                   `thenNF_Tc` \ dflags ->
131                            check (isFFIDynArgumentTy arg1_ty)
132                                  (illegalForeignTyErr argument arg1_ty)                 `thenNF_Tc_`
133                            checkForeignArgs (isFFIArgumentTy dflags safety) arg_tys     `thenNF_Tc_`
134                            checkForeignRes nonIOok (isFFIImportResultTy dflags) res_ty
135
136   | otherwise           -- Normal foreign import
137   = checkCg (if isCasmTarget target
138              then checkC else checkCOrAsmOrDotNetOrInterp)      `thenNF_Tc_`
139     checkCTarget target                                         `thenNF_Tc_`
140     getDOptsTc                                                  `thenNF_Tc` \ dflags ->
141     checkForeignArgs (isFFIArgumentTy dflags safety) arg_tys    `thenNF_Tc_`
142     checkForeignRes nonIOok (isFFIImportResultTy dflags) res_ty
143
144 -- This makes a convenient place to check
145 -- that the C identifier is valid for C
146 checkCTarget (StaticTarget str) 
147   = checkCg checkCOrAsmOrDotNetOrInterp         `thenNF_Tc_`
148     check (isCLabelString str) (badCName str)
149
150 checkCTarget (CasmTarget _)
151   = checkCg checkC
152 \end{code}
153
154 On a SPARC, with foreign export dynamic, due to a giant hack when building
155 adjustor thunks, we only allow 16 bytes of arguments!
156
157 So for example, args (Int,Double,Int) would be OK (1+2+1)
158 as would (Int,Int,Int,Int) (1+1+1+1) but not (Int,Double,Double) (1+2+2).
159
160 On an Alpha, due to a similar hack, we only allow 4 integer arguments with
161 foreign export dynamic (i.e., 32 bytes of arguments after padding each
162 argument to a quadword, excluding floating-point arguments).
163
164 The check is needed for both via-C and native-code routes
165
166 \begin{code}
167 #include "nativeGen/NCG.h"
168 #if sparc_TARGET_ARCH
169 checkFEDArgs arg_tys
170   = check (words_of_args <= 4) err
171   where
172     words_of_args = sum (map (getPrimRepSize . typePrimRep) arg_tys)
173     err = ptext SLIT("On SPARC, I can only handle 4 words of arguments to foreign export dynamic")
174 #else
175 #if alpha_TARGET_ARCH
176 checkFEDArgs arg_tys
177   = check (integral_args <= 4) err
178   where
179     integral_args = sum (map getPrimRepSize $
180                          filter (not . isFloatingRep) $
181                          map typePrimRep arg_tys)
182     err = ptext SLIT("On Alpha, I can only handle 4 non-floating-point arguments to foreign export dynamic")
183 #else
184 checkFEDArgs arg_tys = returnNF_Tc ()
185 #endif
186 #endif
187 \end{code}
188
189
190 %************************************************************************
191 %*                                                                      *
192 \subsection{Exports}
193 %*                                                                      *
194 %************************************************************************
195
196 \begin{code}
197 tcForeignExports :: Module -> [RenamedHsDecl] 
198                  -> TcM (LIE, TcMonoBinds, [TcForeignExportDecl])
199 tcForeignExports mod decls = 
200    foldlTc combine (emptyLIE, EmptyMonoBinds, [])
201      [foreign_decl | ForD foreign_decl <- decls, isForeignExport foreign_decl]
202   where
203    combine (lie, binds, fs) fe = 
204        tcFExport mod fe `thenTc ` \ (a_lie, b, f) ->
205        returnTc (lie `plusLIE` a_lie, b `AndMonoBinds` binds, f:fs)
206
207 tcFExport :: Module -> RenamedForeignDecl -> TcM (LIE, TcMonoBinds, TcForeignExportDecl)
208 tcFExport mod fo@(ForeignExport nm hs_ty spec isDeprec src_loc) =
209    tcAddSrcLoc src_loc                  $
210    tcAddErrCtxt (foreignDeclCtxt fo)    $
211
212    tcHsSigType (ForSigCtxt nm) hs_ty    `thenTc` \ sig_ty ->
213    tcExpr (HsVar nm) sig_ty             `thenTc` \ (rhs, lie) ->
214
215    tcCheckFEType sig_ty spec            `thenTc_`
216
217           -- we're exporting a function, but at a type possibly more
218           -- constrained than its declared/inferred type. Hence the need
219           -- to create a local binding which will call the exported function
220           -- at a particular type (and, maybe, overloading).
221
222    tcGetUnique                          `thenNF_Tc` \ uniq ->
223    let
224         gnm  = mkGlobalName uniq mod (mkForeignExportOcc (getOccName nm)) src_loc
225         id   = setIdLocalExported (mkLocalId gnm sig_ty)
226         bind = VarMonoBind id rhs
227    in
228    returnTc (lie, bind, ForeignExport id undefined spec isDeprec src_loc)
229 \end{code}
230
231 ------------ Checking argument types for foreign export ----------------------
232
233 \begin{code}
234 tcCheckFEType sig_ty (CExport (CExportStatic str _))
235   = check (isCLabelString str) (badCName str)           `thenNF_Tc_`
236     checkForeignArgs isFFIExternalTy arg_tys            `thenNF_Tc_`
237     checkForeignRes nonIOok isFFIExportResultTy res_ty
238   where
239       -- Drop the foralls before inspecting n
240       -- the structure of the foreign type.
241     (_, t_ty) = tcSplitForAllTys sig_ty
242     (arg_tys, res_ty) = tcSplitFunTys t_ty
243 \end{code}
244
245
246
247 %************************************************************************
248 %*                                                                      *
249 \subsection{Miscellaneous}
250 %*                                                                      *
251 %************************************************************************
252
253 \begin{code}
254 ------------ Checking argument types for foreign import ----------------------
255 checkForeignArgs :: (Type -> Bool) -> [Type] -> NF_TcM ()
256 checkForeignArgs pred tys
257   = mapNF_Tc go tys             `thenNF_Tc_` 
258     returnNF_Tc ()
259   where
260     go ty = check (pred ty) (illegalForeignTyErr argument ty)   `thenNF_Tc_`
261             warnTc (isForeignPtrTy ty) foreignPtrWarn
262     --
263     foreignPtrWarn = 
264       text "`ForeignPtr' as argument type in a foreign import is deprecated"
265
266 ------------ Checking result types for foreign calls ----------------------
267 -- Check that the type has the form 
268 --    (IO t) or (t) , and that t satisfies the given predicate.
269 --
270 checkForeignRes :: Bool -> (Type -> Bool) -> Type -> NF_TcM ()
271
272 nonIOok  = True
273 mustBeIO = False
274
275 checkForeignRes non_io_result_ok pred_res_ty ty
276  = case tcSplitTyConApp_maybe ty of
277       Just (io, [res_ty]) 
278         | io `hasKey` ioTyConKey && pred_res_ty res_ty 
279         -> returnNF_Tc ()
280       _   
281         -> check (non_io_result_ok && pred_res_ty ty) 
282                  (illegalForeignTyErr result ty)
283 \end{code}
284
285 \begin{code} 
286 checkDotNet HscILX = Nothing
287 checkDotNet other  = Just (text "requires .NET code generation (-filx)")
288
289 checkC HscC  = Nothing
290 checkC other = Just (text "requires C code generation (-fvia-C)")
291                            
292 checkCOrAsm HscC   = Nothing
293 checkCOrAsm HscAsm = Nothing
294 checkCOrAsm other  
295    = Just (text "requires via-C or native code generation (-fvia-C)")
296
297 checkCOrAsmOrInterp HscC           = Nothing
298 checkCOrAsmOrInterp HscAsm         = Nothing
299 checkCOrAsmOrInterp HscInterpreted = Nothing
300 checkCOrAsmOrInterp other  
301    = Just (text "requires interpreted, C or native code generation")
302
303 checkCOrAsmOrDotNet HscC   = Nothing
304 checkCOrAsmOrDotNet HscAsm = Nothing
305 checkCOrAsmOrDotNet HscILX = Nothing
306 checkCOrAsmOrDotNet other  
307    = Just (text "requires C, native or .NET ILX code generation")
308
309 checkCOrAsmOrDotNetOrInterp HscC           = Nothing
310 checkCOrAsmOrDotNetOrInterp HscAsm         = Nothing
311 checkCOrAsmOrDotNetOrInterp HscILX         = Nothing
312 checkCOrAsmOrDotNetOrInterp HscInterpreted = Nothing
313 checkCOrAsmOrDotNetOrInterp other  
314    = Just (text "requires interpreted, C, native or .NET ILX code generation")
315
316 checkCg check
317  = getDOptsTc           `thenNF_Tc` \ dflags ->
318    let hscLang = dopt_HscLang dflags in
319    case hscLang of
320      HscNothing -> returnNF_Tc ()
321      otherwise  ->
322        case check hscLang of
323          Nothing  -> returnNF_Tc ()
324          Just err -> addErrTc (text "Illegal foreign declaration:" <+> err)
325 \end{code} 
326                            
327 Warnings
328
329 \begin{code}
330 check :: Bool -> Message -> NF_TcM ()
331 check True _       = returnTc ()
332 check _    the_err = addErrTc the_err
333
334 illegalForeignTyErr arg_or_res ty
335   = hang (hsep [ptext SLIT("Unacceptable"), arg_or_res, 
336                 ptext SLIT("type in foreign declaration:")])
337          4 (hsep [ppr ty])
338
339 -- Used for 'arg_or_res' argument to illegalForeignTyErr
340 argument = text "argument"
341 result   = text "result"
342
343 badCName :: CLabelString -> Message
344 badCName target 
345    = sep [quotes (ppr target) <+> ptext SLIT("is not a valid C identifier")]
346
347 foreignDeclCtxt fo
348   = hang (ptext SLIT("When checking declaration:"))
349          4 (ppr fo)
350 \end{code}
351