[project @ 2003-05-29 14:39:26 by sof]
[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, mkVanillaGlobal, setIdLocalExported )
36 import IdInfo           ( noCafIdInfo )
37 import PrimRep          ( getPrimRepSize, isFloatingRep )
38 import Type             ( typePrimRep )
39 import OccName          ( mkForeignExportOcc )
40 import Name             ( Name, NamedThing(..), mkExternalName )
41 import TcType           ( Type, tcSplitFunTys, tcSplitTyConApp_maybe,
42                           tcSplitForAllTys, 
43                           isFFIArgumentTy, isFFIImportResultTy, 
44                           isFFIExportResultTy, isFFILabelTy,
45                           isFFIExternalTy, isFFIDynArgumentTy,
46                           isFFIDynResultTy, isFFIDotnetTy, isFFIDotnetObjTy,
47                           toDNType
48                         )
49 import ForeignCall      ( CExportSpec(..), CCallTarget(..), CCallConv(..),
50                           isDynamicTarget, isCasmTarget, withDNTypes, DNKind(..), DNCallSpec(..) ) 
51 import CStrings         ( CLabelString, isCLabelString )
52 import PrelNames        ( hasKey, ioTyConKey )
53 import CmdLineOpts      ( dopt_HscLang, HscLang(..) )
54 import Outputable
55
56 \end{code}
57
58 \begin{code}
59 -- Defines a binding
60 isForeignImport :: ForeignDecl name -> Bool
61 isForeignImport (ForeignImport _ _ _ _ _) = True
62 isForeignImport _                         = False
63
64 -- Exports a binding
65 isForeignExport :: ForeignDecl name -> Bool
66 isForeignExport (ForeignExport _ _ _ _ _) = True
67 isForeignExport _                         = False
68 \end{code}
69
70 %************************************************************************
71 %*                                                                      *
72 \subsection{Imports}
73 %*                                                                      *
74 %************************************************************************
75
76 \begin{code}
77 tcForeignImports :: [ForeignDecl Name] -> TcM ([Id], [TypecheckedForeignDecl])
78 tcForeignImports decls
79   = mapAndUnzipM tcFImport (filter isForeignImport decls)
80
81 tcFImport :: RenamedForeignDecl -> TcM (Id, TypecheckedForeignDecl)
82 tcFImport fo@(ForeignImport nm hs_ty imp_decl isDeprec src_loc)
83  = addSrcLoc src_loc                    $
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 id undefined imp_decl' isDeprec src_loc)
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 (if isCasmTarget target
159              then checkC else checkCOrAsmOrDotNetOrInterp)      `thenM_`
160     checkCTarget target                                         `thenM_`
161     getDOpts                                                    `thenM` \ dflags ->
162     checkForeignArgs (isFFIArgumentTy dflags safety) arg_tys    `thenM_`
163     checkForeignRes nonIOok (isFFIImportResultTy dflags) res_ty `thenM_`
164     return idecl
165
166 -- This makes a convenient place to check
167 -- that the C identifier is valid for C
168 checkCTarget (StaticTarget str) 
169   = checkCg checkCOrAsmOrDotNetOrInterp         `thenM_`
170     check (isCLabelString str) (badCName str)
171
172 checkCTarget (CasmTarget _)
173   = checkCg checkC
174 \end{code}
175
176 On an Alpha, with foreign export dynamic, due to a giant hack when
177 building adjustor thunks, we only allow 4 integer arguments with
178 foreign export dynamic (i.e., 32 bytes of arguments after padding each
179 argument to a quadword, excluding floating-point arguments).
180
181 The check is needed for both via-C and native-code routes
182
183 \begin{code}
184 #include "nativeGen/NCG.h"
185 #if alpha_TARGET_ARCH
186 checkFEDArgs arg_tys
187   = check (integral_args <= 4) err
188   where
189     integral_args = sum (map getPrimRepSize $
190                          filter (not . isFloatingRep) $
191                          map typePrimRep arg_tys)
192     err = ptext SLIT("On Alpha, I can only handle 4 non-floating-point arguments to foreign export dynamic")
193 #else
194 checkFEDArgs arg_tys = returnM ()
195 #endif
196 \end{code}
197
198
199 %************************************************************************
200 %*                                                                      *
201 \subsection{Exports}
202 %*                                                                      *
203 %************************************************************************
204
205 \begin{code}
206 tcForeignExports :: [ForeignDecl Name] 
207                  -> TcM (TcMonoBinds, [TcForeignDecl])
208 tcForeignExports decls
209   = foldlM combine (EmptyMonoBinds, []) (filter isForeignExport decls)
210   where
211    combine (binds, fs) fe = 
212        tcFExport fe     `thenM ` \ (b, f) ->
213        returnM (b `AndMonoBinds` binds, f:fs)
214
215 tcFExport :: RenamedForeignDecl -> TcM (TcMonoBinds, TcForeignDecl)
216 tcFExport fo@(ForeignExport nm hs_ty spec isDeprec src_loc) =
217    addSrcLoc src_loc                    $
218    addErrCtxt (foreignDeclCtxt fo)      $
219
220    tcHsSigType (ForSigCtxt nm) hs_ty    `thenM` \ sig_ty ->
221    tcCheckSigma (HsVar nm) sig_ty       `thenM` \ rhs ->
222
223    tcCheckFEType sig_ty spec            `thenM_`
224
225           -- we're exporting a function, but at a type possibly more
226           -- constrained than its declared/inferred type. Hence the need
227           -- to create a local binding which will call the exported function
228           -- at a particular type (and, maybe, overloading).
229
230    newUnique                    `thenM` \ uniq ->
231    getModule                    `thenM` \ mod ->
232    let
233         gnm  = mkExternalName uniq mod (mkForeignExportOcc (getOccName nm)) src_loc
234         id   = setIdLocalExported (mkLocalId gnm sig_ty)
235         bind = VarMonoBind id rhs
236    in
237    returnM (bind, ForeignExport id undefined spec isDeprec src_loc)
238 \end{code}
239
240 ------------ Checking argument types for foreign export ----------------------
241
242 \begin{code}
243 tcCheckFEType sig_ty (CExport (CExportStatic str _))
244   = check (isCLabelString str) (badCName str)           `thenM_`
245     checkForeignArgs isFFIExternalTy arg_tys            `thenM_`
246     checkForeignRes nonIOok isFFIExportResultTy res_ty
247   where
248       -- Drop the foralls before inspecting n
249       -- the structure of the foreign type.
250     (_, t_ty) = tcSplitForAllTys sig_ty
251     (arg_tys, res_ty) = tcSplitFunTys t_ty
252 \end{code}
253
254
255
256 %************************************************************************
257 %*                                                                      *
258 \subsection{Miscellaneous}
259 %*                                                                      *
260 %************************************************************************
261
262 \begin{code}
263 ------------ Checking argument types for foreign import ----------------------
264 checkForeignArgs :: (Type -> Bool) -> [Type] -> TcM ()
265 checkForeignArgs pred tys
266   = mappM go tys                `thenM_` 
267     returnM ()
268   where
269     go ty = check (pred ty) (illegalForeignTyErr argument ty)
270
271 ------------ Checking result types for foreign calls ----------------------
272 -- Check that the type has the form 
273 --    (IO t) or (t) , and that t satisfies the given predicate.
274 --
275 checkForeignRes :: Bool -> (Type -> Bool) -> Type -> TcM ()
276
277 nonIOok  = True
278 mustBeIO = False
279
280 checkForeignRes non_io_result_ok pred_res_ty ty
281  = case tcSplitTyConApp_maybe ty of
282       Just (io, [res_ty]) 
283         | io `hasKey` ioTyConKey && pred_res_ty res_ty 
284         -> returnM ()
285       _   
286         -> check (non_io_result_ok && pred_res_ty ty) 
287                  (illegalForeignTyErr result ty)
288 \end{code}
289
290 \begin{code}
291 checkDotnet HscILX = Nothing
292 #if defined(mingw32_TARGET_OS)
293 checkDotnet HscC   = Nothing
294 checkDotnet _      = Just (text "requires C code generation (-fvia-C)")
295 #else
296 checkDotnet other  = Just (text "requires .NET support (-filx or win32)")
297 #endif
298
299 checkC HscC  = Nothing
300 checkC other = Just (text "requires C code generation (-fvia-C)")
301                            
302 checkCOrAsm HscC   = Nothing
303 checkCOrAsm HscAsm = Nothing
304 checkCOrAsm other  
305    = Just (text "requires via-C or native code generation (-fvia-C)")
306
307 checkCOrAsmOrInterp HscC           = Nothing
308 checkCOrAsmOrInterp HscAsm         = Nothing
309 checkCOrAsmOrInterp HscInterpreted = Nothing
310 checkCOrAsmOrInterp other  
311    = Just (text "requires interpreted, C or native code generation")
312
313 checkCOrAsmOrDotNet HscC   = Nothing
314 checkCOrAsmOrDotNet HscAsm = Nothing
315 checkCOrAsmOrDotNet HscILX = Nothing
316 checkCOrAsmOrDotNet other  
317    = Just (text "requires C, native or .NET ILX code generation")
318
319 checkCOrAsmOrDotNetOrInterp HscC           = Nothing
320 checkCOrAsmOrDotNetOrInterp HscAsm         = Nothing
321 checkCOrAsmOrDotNetOrInterp HscILX         = Nothing
322 checkCOrAsmOrDotNetOrInterp HscInterpreted = Nothing
323 checkCOrAsmOrDotNetOrInterp other  
324    = Just (text "requires interpreted, C, native or .NET ILX code generation")
325
326 checkCg check
327  = getDOpts             `thenM` \ dflags ->
328    let hscLang = dopt_HscLang dflags in
329    case hscLang of
330      HscNothing -> returnM ()
331      otherwise  ->
332        case check hscLang of
333          Nothing  -> returnM ()
334          Just err -> addErrTc (text "Illegal foreign declaration:" <+> err)
335 \end{code} 
336                            
337 Warnings
338
339 \begin{code}
340 check :: Bool -> Message -> TcM ()
341 check True _       = returnM ()
342 check _    the_err = addErrTc the_err
343
344 illegalForeignTyErr arg_or_res ty
345   = hang (hsep [ptext SLIT("Unacceptable"), arg_or_res, 
346                 ptext SLIT("type in foreign declaration:")])
347          4 (hsep [ppr ty])
348
349 -- Used for 'arg_or_res' argument to illegalForeignTyErr
350 argument = text "argument"
351 result   = text "result"
352
353 badCName :: CLabelString -> Message
354 badCName target 
355    = sep [quotes (ppr target) <+> ptext SLIT("is not a valid C identifier")]
356
357 foreignDeclCtxt fo
358   = hang (ptext SLIT("When checking declaration:"))
359          4 (ppr fo)
360
361 illegalDNMethodSig 
362   = ptext SLIT("'This pointer' expected as last argument")
363
364 \end{code}
365