accb750f2adac7d871b4e824bcddba98bdf42180
[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 "config.h"
21 #include "HsVersions.h"
22
23 import HsSyn            ( ForeignDecl(..), HsExpr(..),
24                           MonoBinds(..), ForeignImport(..), ForeignExport(..),
25                           CImportSpec(..)
26                         )
27 import RnHsSyn          ( RenamedForeignDecl )
28
29 import TcRnMonad
30 import TcMonoType       ( tcHsSigType, UserTypeCtxt(..) )
31 import TcHsSyn          ( TcMonoBinds, TypecheckedForeignDecl, TcForeignDecl )
32 import TcExpr           ( tcCheckSigma )                        
33
34 import ErrUtils         ( Message )
35 import Id               ( Id, mkLocalId, setIdLocalExported )
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, isFFIDotnetTy, isFFIDotnetObjTy,
46                           toDNType
47                         )
48 import ForeignCall      ( CExportSpec(..), CCallTarget(..), 
49                           isDynamicTarget, isCasmTarget, withDNTypes, DNKind(..), DNCallSpec(..) ) 
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 :: [ForeignDecl Name] -> TcM ([Id], [TypecheckedForeignDecl])
77 tcForeignImports decls
78   = mapAndUnzipM tcFImport (filter isForeignImport decls)
79
80 tcFImport :: RenamedForeignDecl -> TcM (Id, TypecheckedForeignDecl)
81 tcFImport fo@(ForeignImport nm hs_ty imp_decl isDeprec src_loc)
82  = addSrcLoc src_loc                    $
83    addErrCtxt (foreignDeclCtxt fo)      $
84    tcHsSigType (ForSigCtxt nm) hs_ty    `thenM` \ sig_ty ->
85    let 
86       -- drop the foralls before inspecting the structure
87       -- of the foreign type.
88         (_, t_ty)         = tcSplitForAllTys sig_ty
89         (arg_tys, res_ty) = tcSplitFunTys t_ty
90         id                = mkLocalId nm sig_ty
91                 -- Use a LocalId to obey the invariant that locally-defined 
92                 -- things are LocalIds.  However, it does not need zonking,
93                 -- (so TcHsSyn.zonkForeignExports ignores it).
94    in
95    tcCheckFIType sig_ty arg_tys res_ty imp_decl         `thenM` \ imp_decl' -> 
96    -- can't use sig_ty here because it :: Type and we need HsType Id
97    -- hence the undefined
98    returnM (id, ForeignImport id undefined imp_decl' isDeprec src_loc)
99 \end{code}
100
101
102 ------------ Checking types for foreign import ----------------------
103 \begin{code}
104 tcCheckFIType _ arg_tys res_ty (DNImport spec)
105   = checkCg checkDotnet  `thenM_`
106     getDOpts             `thenM`  \ dflags ->
107     checkForeignArgs (isFFIDotnetTy dflags) arg_tys     `thenM_`
108     checkForeignRes True{-non IO ok-} (isFFIDotnetTy dflags) res_ty `thenM_`
109     let (DNCallSpec isStatic kind _ _ _ _) = spec in
110     (case kind of
111        DNMethod | not isStatic ->
112          case arg_tys of
113            [] -> addErrTc illegalDNMethodSig
114            _  
115             | not (isFFIDotnetObjTy (last arg_tys)) -> addErrTc illegalDNMethodSig
116             | otherwise -> returnM ()
117        _ -> returnM ()) `thenM_`
118     returnM (DNImport (withDNTypes spec (map toDNType arg_tys) (toDNType res_ty)))
119
120 tcCheckFIType sig_ty arg_tys res_ty idecl@(CImport _ _ _ _ (CLabel _))
121   = checkCg checkCOrAsm         `thenM_`
122     check (isFFILabelTy sig_ty) (illegalForeignTyErr empty sig_ty) `thenM_`
123     return idecl
124
125 tcCheckFIType sig_ty arg_tys res_ty idecl@(CImport cconv _ _ _ CWrapper)
126   =     -- Foreign wrapper (former f.e.d.)
127         -- The type must be of the form ft -> IO (FunPtr ft), where ft is a
128         -- valid foreign type.  For legacy reasons ft -> IO (Ptr ft) as well
129         -- as ft -> IO Addr is accepted, too.  The use of the latter two forms
130         -- is DEPRECATED, though.
131     checkCg checkCOrAsmOrInterp `thenM_`
132     (case arg_tys of
133         [arg1_ty] -> checkForeignArgs isFFIExternalTy arg1_tys               `thenM_`
134                      checkForeignRes nonIOok  isFFIExportResultTy res1_ty    `thenM_`
135                      checkForeignRes mustBeIO isFFIDynResultTy    res_ty     `thenM_`
136                      checkFEDArgs arg1_tys
137                   where
138                      (arg1_tys, res1_ty) = tcSplitFunTys arg1_ty
139         other -> addErrTc (illegalForeignTyErr empty sig_ty)    )            `thenM_`
140     return idecl
141
142 tcCheckFIType sig_ty arg_tys res_ty idecl@(CImport _ safety _ _ (CFunction target))
143   | isDynamicTarget target      -- Foreign import dynamic
144   = checkCg checkCOrAsmOrInterp         `thenM_`
145     case arg_tys of             -- The first arg must be Ptr, FunPtr, or Addr
146       []                -> 
147         check False (illegalForeignTyErr empty sig_ty) `thenM_`
148         return idecl
149       (arg1_ty:arg_tys) -> 
150         getDOpts                                                     `thenM` \ dflags ->
151         check (isFFIDynArgumentTy arg1_ty)
152               (illegalForeignTyErr argument arg1_ty)                 `thenM_`
153         checkForeignArgs (isFFIArgumentTy dflags safety) arg_tys     `thenM_`
154         checkForeignRes nonIOok (isFFIImportResultTy dflags) res_ty  `thenM_`
155         return idecl
156   | otherwise           -- Normal foreign import
157   = checkCg (if isCasmTarget target
158              then checkC else 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
171 checkCTarget (CasmTarget _)
172   = checkCg checkC
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 <= 4) err
187   where
188     integral_args = sum (map getPrimRepSize $
189                          filter (not . isFloatingRep) $
190                          map typePrimRep arg_tys)
191     err = ptext SLIT("On Alpha, I can only handle 4 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 :: [ForeignDecl Name] 
206                  -> TcM (TcMonoBinds, [TcForeignDecl])
207 tcForeignExports decls
208   = foldlM combine (EmptyMonoBinds, []) (filter isForeignExport decls)
209   where
210    combine (binds, fs) fe = 
211        tcFExport fe     `thenM ` \ (b, f) ->
212        returnM (b `AndMonoBinds` binds, f:fs)
213
214 tcFExport :: RenamedForeignDecl -> TcM (TcMonoBinds, TcForeignDecl)
215 tcFExport fo@(ForeignExport nm hs_ty spec isDeprec src_loc) =
216    addSrcLoc src_loc                    $
217    addErrCtxt (foreignDeclCtxt fo)      $
218
219    tcHsSigType (ForSigCtxt nm) hs_ty    `thenM` \ sig_ty ->
220    tcCheckSigma (HsVar nm) sig_ty       `thenM` \ rhs ->
221
222    tcCheckFEType sig_ty spec            `thenM_`
223
224           -- we're exporting a function, but at a type possibly more
225           -- constrained than its declared/inferred type. Hence the need
226           -- to create a local binding which will call the exported function
227           -- at a particular type (and, maybe, overloading).
228
229    newUnique                    `thenM` \ uniq ->
230    getModule                    `thenM` \ mod ->
231    let
232         gnm  = mkExternalName uniq mod (mkForeignExportOcc (getOccName nm)) src_loc
233         id   = setIdLocalExported (mkLocalId gnm sig_ty)
234         bind = VarMonoBind id rhs
235    in
236    returnM (bind, ForeignExport id undefined spec isDeprec src_loc)
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 checkC HscC  = Nothing
299 checkC other = Just (text "requires C code generation (-fvia-C)")
300                            
301 checkCOrAsm HscC   = Nothing
302 checkCOrAsm HscAsm = Nothing
303 checkCOrAsm other  
304    = Just (text "requires via-C or native code generation (-fvia-C)")
305
306 checkCOrAsmOrInterp HscC           = Nothing
307 checkCOrAsmOrInterp HscAsm         = Nothing
308 checkCOrAsmOrInterp HscInterpreted = Nothing
309 checkCOrAsmOrInterp other  
310    = Just (text "requires interpreted, C or native code generation")
311
312 checkCOrAsmOrDotNet HscC   = Nothing
313 checkCOrAsmOrDotNet HscAsm = Nothing
314 checkCOrAsmOrDotNet HscILX = Nothing
315 checkCOrAsmOrDotNet other  
316    = Just (text "requires C, native or .NET ILX code generation")
317
318 checkCOrAsmOrDotNetOrInterp HscC           = Nothing
319 checkCOrAsmOrDotNetOrInterp HscAsm         = Nothing
320 checkCOrAsmOrDotNetOrInterp HscILX         = Nothing
321 checkCOrAsmOrDotNetOrInterp HscInterpreted = Nothing
322 checkCOrAsmOrDotNetOrInterp other  
323    = Just (text "requires interpreted, C, native or .NET ILX code generation")
324
325 checkCg check
326  = getDOpts             `thenM` \ dflags ->
327    let hscLang = dopt_HscLang dflags in
328    case hscLang of
329      HscNothing -> returnM ()
330      otherwise  ->
331        case check hscLang of
332          Nothing  -> returnM ()
333          Just err -> addErrTc (text "Illegal foreign declaration:" <+> err)
334 \end{code} 
335                            
336 Warnings
337
338 \begin{code}
339 check :: Bool -> Message -> TcM ()
340 check True _       = returnM ()
341 check _    the_err = addErrTc the_err
342
343 illegalForeignTyErr arg_or_res ty
344   = hang (hsep [ptext SLIT("Unacceptable"), arg_or_res, 
345                 ptext SLIT("type in foreign declaration:")])
346          4 (hsep [ppr ty])
347
348 -- Used for 'arg_or_res' argument to illegalForeignTyErr
349 argument = text "argument"
350 result   = text "result"
351
352 badCName :: CLabelString -> Message
353 badCName target 
354    = sep [quotes (ppr target) <+> ptext SLIT("is not a valid C identifier")]
355
356 foreignDeclCtxt fo
357   = hang (ptext SLIT("When checking declaration:"))
358          4 (ppr fo)
359
360 illegalDNMethodSig 
361   = ptext SLIT("'This pointer' expected as last argument")
362
363 \end{code}
364