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