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