remove empty dir
[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
23
24 import TcRnMonad
25 import TcHsType         ( tcHsSigType, UserTypeCtxt(..) )
26 import TcExpr           ( tcPolyExpr )                  
27
28 import ForeignCall      ( CCallConv(..) )
29 import ErrUtils         ( Message )
30 import Id               ( Id, mkLocalId, mkExportedLocalId )
31 #if alpha_TARGET_ARCH
32 import Type             ( typePrimRep )
33 import SMRep            ( argMachRep, primRepToCgRep, primRepHint )
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 DynFlags         ( DynFlags(..), HscTarget(..) )
50 import Outputable
51 import SrcLoc           ( Located(..), srcSpanStart )
52 import Bag              ( consBag )
53
54 #if alpha_TARGET_ARCH
55 import MachOp           ( machRepByteWidth, MachHint(FloatHint) )
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     checkCConv cconv            `thenM_`
134     (case arg_tys of
135         [arg1_ty] -> checkForeignArgs isFFIExternalTy arg1_tys               `thenM_`
136                      checkForeignRes nonIOok  isFFIExportResultTy res1_ty    `thenM_`
137                      checkForeignRes mustBeIO isFFIDynResultTy    res_ty     `thenM_`
138                      checkFEDArgs arg1_tys
139                   where
140                      (arg1_tys, res1_ty) = tcSplitFunTys arg1_ty
141         other -> addErrTc (illegalForeignTyErr empty sig_ty)    )            `thenM_`
142     return idecl
143
144 tcCheckFIType sig_ty arg_tys res_ty idecl@(CImport cconv safety _ _ (CFunction target))
145   | isDynamicTarget target      -- Foreign import dynamic
146   = checkCg checkCOrAsmOrInterp         `thenM_`
147     checkCConv cconv                    `thenM_`
148     case arg_tys of             -- The first arg must be Ptr, FunPtr, or Addr
149       []                -> 
150         check False (illegalForeignTyErr empty sig_ty) `thenM_`
151         return idecl
152       (arg1_ty:arg_tys) -> 
153         getDOpts                                                     `thenM` \ dflags ->
154         check (isFFIDynArgumentTy arg1_ty)
155               (illegalForeignTyErr argument arg1_ty)                 `thenM_`
156         checkForeignArgs (isFFIArgumentTy dflags safety) arg_tys     `thenM_`
157         checkForeignRes nonIOok (isFFIImportResultTy dflags) res_ty  `thenM_`
158         return idecl
159   | otherwise           -- Normal foreign import
160   = checkCg (checkCOrAsmOrDotNetOrInterp)                       `thenM_`
161     checkCConv cconv                                            `thenM_`
162     checkCTarget target                                         `thenM_`
163     getDOpts                                                    `thenM` \ dflags ->
164     checkForeignArgs (isFFIArgumentTy dflags safety) arg_tys    `thenM_`
165     checkForeignRes nonIOok (isFFIImportResultTy dflags) res_ty `thenM_`
166     return idecl
167
168 -- This makes a convenient place to check
169 -- that the C identifier is valid for C
170 checkCTarget (StaticTarget str) 
171   = checkCg checkCOrAsmOrDotNetOrInterp         `thenM_`
172     check (isCLabelString str) (badCName str)
173 \end{code}
174
175 On an Alpha, with foreign export dynamic, due to a giant hack when
176 building adjustor thunks, we only allow 4 integer arguments with
177 foreign export dynamic (i.e., 32 bytes of arguments after padding each
178 argument to a quadword, excluding floating-point arguments).
179
180 The check is needed for both via-C and native-code routes
181
182 \begin{code}
183 #include "nativeGen/NCG.h"
184 #if alpha_TARGET_ARCH
185 checkFEDArgs arg_tys
186   = check (integral_args <= 32) err
187   where
188     integral_args = sum [ (machRepByteWidth . argMachRep . primRepToCgRep) prim_rep
189                         | prim_rep <- map typePrimRep arg_tys,
190                           primRepHint prim_rep /= FloatHint ]
191     err = ptext SLIT("On Alpha, I can only handle 32 bytes of non-floating-point arguments to foreign export dynamic")
192 #else
193 checkFEDArgs arg_tys = returnM ()
194 #endif
195 \end{code}
196
197
198 %************************************************************************
199 %*                                                                      *
200 \subsection{Exports}
201 %*                                                                      *
202 %************************************************************************
203
204 \begin{code}
205 tcForeignExports :: [LForeignDecl Name] 
206                  -> TcM (LHsBinds TcId, [LForeignDecl TcId])
207 tcForeignExports decls
208   = foldlM combine (emptyLHsBinds, []) (filter isForeignExport decls)
209   where
210    combine (binds, fs) fe = 
211        wrapLocSndM tcFExport fe `thenM` \ (b, f) ->
212        returnM (b `consBag` binds, f:fs)
213
214 tcFExport :: ForeignDecl Name -> TcM (LHsBind Id, ForeignDecl Id)
215 tcFExport fo@(ForeignExport (L loc nm) hs_ty spec isDeprec) =
216    addErrCtxt (foreignDeclCtxt fo)      $
217
218    tcHsSigType (ForSigCtxt nm) hs_ty    `thenM` \ sig_ty ->
219    tcPolyExpr (nlHsVar nm) sig_ty       `thenM` \ rhs ->
220
221    tcCheckFEType sig_ty spec            `thenM_`
222
223           -- we're exporting a function, but at a type possibly more
224           -- constrained than its declared/inferred type. Hence the need
225           -- to create a local binding which will call the exported function
226           -- at a particular type (and, maybe, overloading).
227
228    newUnique                    `thenM` \ uniq ->
229    getModule                    `thenM` \ mod ->
230    let
231         gnm  = mkExternalName uniq mod (mkForeignExportOcc (getOccName nm)) 
232                               Nothing (srcSpanStart loc)
233         id   = mkExportedLocalId gnm sig_ty
234         bind = L loc (VarBind id rhs)
235    in
236    returnM (bind, ForeignExport (L loc id) undefined spec isDeprec)
237 \end{code}
238
239 ------------ Checking argument types for foreign export ----------------------
240
241 \begin{code}
242 tcCheckFEType sig_ty (CExport (CExportStatic str _))
243   = check (isCLabelString str) (badCName str)           `thenM_`
244     checkForeignArgs isFFIExternalTy arg_tys            `thenM_`
245     checkForeignRes nonIOok isFFIExportResultTy res_ty
246   where
247       -- Drop the foralls before inspecting n
248       -- the structure of the foreign type.
249     (_, t_ty) = tcSplitForAllTys sig_ty
250     (arg_tys, res_ty) = tcSplitFunTys t_ty
251 \end{code}
252
253
254
255 %************************************************************************
256 %*                                                                      *
257 \subsection{Miscellaneous}
258 %*                                                                      *
259 %************************************************************************
260
261 \begin{code}
262 ------------ Checking argument types for foreign import ----------------------
263 checkForeignArgs :: (Type -> Bool) -> [Type] -> TcM ()
264 checkForeignArgs pred tys
265   = mappM go tys                `thenM_` 
266     returnM ()
267   where
268     go ty = check (pred ty) (illegalForeignTyErr argument ty)
269
270 ------------ Checking result types for foreign calls ----------------------
271 -- Check that the type has the form 
272 --    (IO t) or (t) , and that t satisfies the given predicate.
273 --
274 checkForeignRes :: Bool -> (Type -> Bool) -> Type -> TcM ()
275
276 nonIOok  = True
277 mustBeIO = False
278
279 checkForeignRes non_io_result_ok pred_res_ty ty
280  = case tcSplitTyConApp_maybe ty of
281       Just (io, [res_ty]) 
282         | io `hasKey` ioTyConKey && pred_res_ty res_ty 
283         -> returnM ()
284       _   
285         -> check (non_io_result_ok && pred_res_ty ty) 
286                  (illegalForeignTyErr result ty)
287 \end{code}
288
289 \begin{code}
290 checkDotnet HscILX = Nothing
291 #if defined(mingw32_TARGET_OS)
292 checkDotnet HscC   = Nothing
293 checkDotnet _      = Just (text "requires C code generation (-fvia-C)")
294 #else
295 checkDotnet other  = Just (text "requires .NET support (-filx or win32)")
296 #endif
297
298 checkCOrAsm HscC   = Nothing
299 checkCOrAsm HscAsm = Nothing
300 checkCOrAsm other  
301    = Just (text "requires via-C or native code generation (-fvia-C)")
302
303 checkCOrAsmOrInterp HscC           = Nothing
304 checkCOrAsmOrInterp HscAsm         = Nothing
305 checkCOrAsmOrInterp HscInterpreted = Nothing
306 checkCOrAsmOrInterp other  
307    = Just (text "requires interpreted, C or native 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  = getDOpts             `thenM` \ dflags ->
318    let target = hscTarget dflags in
319    case target of
320      HscNothing -> returnM ()
321      otherwise  ->
322        case check target of
323          Nothing  -> returnM ()
324          Just err -> addErrTc (text "Illegal foreign declaration:" <+> err)
325 \end{code} 
326                            
327 Calling conventions
328
329 \begin{code}
330 checkCConv :: CCallConv -> TcM ()
331 checkCConv CCallConv  = return ()
332 #if i386_TARGET_ARCH
333 checkCConv StdCallConv = return ()
334 #else
335 checkCConv StdCallConv = addErrTc (text "calling convention not supported on this architecture: stdcall")
336 #endif
337 \end{code}
338
339 Warnings
340
341 \begin{code}
342 check :: Bool -> Message -> TcM ()
343 check True _       = returnM ()
344 check _    the_err = addErrTc the_err
345
346 illegalForeignTyErr arg_or_res ty
347   = hang (hsep [ptext SLIT("Unacceptable"), arg_or_res, 
348                 ptext SLIT("type in foreign declaration:")])
349          4 (hsep [ppr ty])
350
351 -- Used for 'arg_or_res' argument to illegalForeignTyErr
352 argument = text "argument"
353 result   = text "result"
354
355 badCName :: CLabelString -> Message
356 badCName target 
357    = sep [quotes (ppr target) <+> ptext SLIT("is not a valid C identifier")]
358
359 foreignDeclCtxt fo
360   = hang (ptext SLIT("When checking declaration:"))
361          4 (ppr fo)
362
363 illegalDNMethodSig 
364   = ptext SLIT("'This pointer' expected as last argument")
365
366 \end{code}
367