[project @ 2002-09-13 15:02:25 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 "HsVersions.h"
21
22 import HsSyn            ( HsDecl(..), ForeignDecl(..), HsExpr(..),
23                           MonoBinds(..), ForeignImport(..), ForeignExport(..),
24                           CImportSpec(..)
25                         )
26 import RnHsSyn          ( RenamedHsDecl, RenamedForeignDecl )
27
28 import TcRnMonad
29 import TcMonoType       ( tcHsSigType, UserTypeCtxt(..) )
30 import TcHsSyn          ( TcMonoBinds, TypecheckedForeignDecl, TcForeignDecl )
31 import TcExpr           ( tcExpr )                      
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             ( 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 :: [RenamedHsDecl] -> TcM ([Id], [TypecheckedForeignDecl])
76 tcForeignImports decls = 
77   mapAndUnzipM tcFImport 
78     [ foreign_decl | ForD foreign_decl <- decls, isForeignImport foreign_decl]
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                = mkVanillaGlobal nm sig_ty noCafIdInfo
91                 -- Foreign-imported things don't neeed zonking etc
92                 -- They are rather like constructors; we make the final
93                 -- Global Id right away.
94    in
95    tcCheckFIType sig_ty arg_tys res_ty imp_decl         `thenM_` 
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 _ _ _ (DNImport _)
105   = checkCg checkDotNet
106
107 tcCheckFIType sig_ty arg_tys res_ty (CImport _ _ _ _ (CLabel _))
108   = checkCg checkCOrAsm         `thenM_`
109     check (isFFILabelTy sig_ty) (illegalForeignTyErr empty sig_ty)
110
111 tcCheckFIType sig_ty arg_tys res_ty (CImport cconv _ _ _ CWrapper)
112   =     -- Foreign wrapper (former f.e.d.)
113         -- The type must be of the form ft -> IO (FunPtr ft), where ft is a
114         -- valid foreign type.  For legacy reasons ft -> IO (Ptr ft) as well
115         -- as ft -> IO Addr is accepted, too.  The use of the latter two forms
116         -- is DEPRECATED, though.
117     checkCg (if cconv == StdCallConv
118                 then checkC
119                 else checkCOrAsmOrInterp)               `thenM_`
120         -- the native code gen can't handle foreign import stdcall "wrapper",
121         -- because it doesn't emit the '@n' suffix on the label of the
122         -- C stub function.  Infrastructure changes are required to make this
123         -- happen; MachLabel will need to carry around information about
124         -- the arity of the foreign call.
125     case arg_tys of
126         [arg1_ty] -> checkForeignArgs isFFIExternalTy arg1_tys                  `thenM_`
127                      checkForeignRes nonIOok  isFFIExportResultTy res1_ty       `thenM_`
128                      checkForeignRes mustBeIO isFFIDynResultTy    res_ty        `thenM_`
129                      checkFEDArgs arg1_tys
130                   where
131                      (arg1_tys, res1_ty) = tcSplitFunTys arg1_ty
132         other -> addErrTc (illegalForeignTyErr empty sig_ty)
133
134 tcCheckFIType sig_ty arg_tys res_ty (CImport _ safety _ _ (CFunction target))
135   | isDynamicTarget target      -- Foreign import dynamic
136   = checkCg checkCOrAsmOrInterp         `thenM_`
137     case arg_tys of             -- The first arg must be Ptr, FunPtr, or Addr
138       []                -> check False (illegalForeignTyErr empty sig_ty)
139       (arg1_ty:arg_tys) -> getDOpts                                                     `thenM` \ dflags ->
140                            check (isFFIDynArgumentTy arg1_ty)
141                                  (illegalForeignTyErr argument arg1_ty)                 `thenM_`
142                            checkForeignArgs (isFFIArgumentTy dflags safety) arg_tys     `thenM_`
143                            checkForeignRes nonIOok (isFFIImportResultTy dflags) res_ty
144
145   | otherwise           -- Normal foreign import
146   = checkCg (if isCasmTarget target
147              then checkC else checkCOrAsmOrDotNetOrInterp)      `thenM_`
148     checkCTarget target                                         `thenM_`
149     getDOpts                                                    `thenM` \ dflags ->
150     checkForeignArgs (isFFIArgumentTy dflags safety) arg_tys    `thenM_`
151     checkForeignRes nonIOok (isFFIImportResultTy dflags) res_ty
152
153 -- This makes a convenient place to check
154 -- that the C identifier is valid for C
155 checkCTarget (StaticTarget str) 
156   = checkCg checkCOrAsmOrDotNetOrInterp         `thenM_`
157     check (isCLabelString str) (badCName str)
158
159 checkCTarget (CasmTarget _)
160   = checkCg checkC
161 \end{code}
162
163 On an Alpha, with foreign export dynamic, due to a giant hack when
164 building adjustor thunks, we only allow 4 integer arguments with
165 foreign export dynamic (i.e., 32 bytes of arguments after padding each
166 argument to a quadword, excluding floating-point arguments).
167
168 The check is needed for both via-C and native-code routes
169
170 \begin{code}
171 #include "nativeGen/NCG.h"
172 #if alpha_TARGET_ARCH
173 checkFEDArgs arg_tys
174   = check (integral_args <= 4) err
175   where
176     integral_args = sum (map getPrimRepSize $
177                          filter (not . isFloatingRep) $
178                          map typePrimRep arg_tys)
179     err = ptext SLIT("On Alpha, I can only handle 4 non-floating-point arguments to foreign export dynamic")
180 #else
181 checkFEDArgs arg_tys = returnM ()
182 #endif
183 \end{code}
184
185
186 %************************************************************************
187 %*                                                                      *
188 \subsection{Exports}
189 %*                                                                      *
190 %************************************************************************
191
192 \begin{code}
193 tcForeignExports :: [RenamedHsDecl] 
194                  -> TcM (TcMonoBinds, [TcForeignDecl])
195 tcForeignExports decls = 
196    foldlM combine (EmptyMonoBinds, [])
197      [foreign_decl | ForD foreign_decl <- decls, isForeignExport foreign_decl]
198   where
199    combine (binds, fs) fe = 
200        tcFExport fe     `thenM ` \ (b, f) ->
201        returnM (b `AndMonoBinds` binds, f:fs)
202
203 tcFExport :: RenamedForeignDecl -> TcM (TcMonoBinds, TcForeignDecl)
204 tcFExport fo@(ForeignExport nm hs_ty spec isDeprec src_loc) =
205    addSrcLoc src_loc                    $
206    addErrCtxt (foreignDeclCtxt fo)      $
207
208    tcHsSigType (ForSigCtxt nm) hs_ty    `thenM` \ sig_ty ->
209    tcExpr (HsVar nm) sig_ty             `thenM` \ rhs ->
210
211    tcCheckFEType sig_ty spec            `thenM_`
212
213           -- we're exporting a function, but at a type possibly more
214           -- constrained than its declared/inferred type. Hence the need
215           -- to create a local binding which will call the exported function
216           -- at a particular type (and, maybe, overloading).
217
218    newUnique                    `thenM` \ uniq ->
219    getModule                    `thenM` \ mod ->
220    let
221         gnm  = mkExternalName uniq mod (mkForeignExportOcc (getOccName nm)) src_loc
222         id   = setIdLocalExported (mkLocalId gnm sig_ty)
223         bind = VarMonoBind id rhs
224    in
225    returnM (bind, ForeignExport id undefined spec isDeprec src_loc)
226 \end{code}
227
228 ------------ Checking argument types for foreign export ----------------------
229
230 \begin{code}
231 tcCheckFEType sig_ty (CExport (CExportStatic str _))
232   = check (isCLabelString str) (badCName str)           `thenM_`
233     checkForeignArgs isFFIExternalTy arg_tys            `thenM_`
234     checkForeignRes nonIOok isFFIExportResultTy res_ty
235   where
236       -- Drop the foralls before inspecting n
237       -- the structure of the foreign type.
238     (_, t_ty) = tcSplitForAllTys sig_ty
239     (arg_tys, res_ty) = tcSplitFunTys t_ty
240 \end{code}
241
242
243
244 %************************************************************************
245 %*                                                                      *
246 \subsection{Miscellaneous}
247 %*                                                                      *
248 %************************************************************************
249
250 \begin{code}
251 ------------ Checking argument types for foreign import ----------------------
252 checkForeignArgs :: (Type -> Bool) -> [Type] -> TcM ()
253 checkForeignArgs pred tys
254   = mappM go tys                `thenM_` 
255     returnM ()
256   where
257     go ty = check (pred ty) (illegalForeignTyErr argument ty)
258
259 ------------ Checking result types for foreign calls ----------------------
260 -- Check that the type has the form 
261 --    (IO t) or (t) , and that t satisfies the given predicate.
262 --
263 checkForeignRes :: Bool -> (Type -> Bool) -> Type -> TcM ()
264
265 nonIOok  = True
266 mustBeIO = False
267
268 checkForeignRes non_io_result_ok pred_res_ty ty
269  = case tcSplitTyConApp_maybe ty of
270       Just (io, [res_ty]) 
271         | io `hasKey` ioTyConKey && pred_res_ty res_ty 
272         -> returnM ()
273       _   
274         -> check (non_io_result_ok && pred_res_ty ty) 
275                  (illegalForeignTyErr result ty)
276 \end{code}
277
278 \begin{code}
279 checkDotNet HscILX = Nothing
280 checkDotNet other  = Just (text "requires .NET code generation (-filx)")
281
282 checkC HscC  = Nothing
283 checkC other = Just (text "requires C code generation (-fvia-C)")
284                            
285 checkCOrAsm HscC   = Nothing
286 checkCOrAsm HscAsm = Nothing
287 checkCOrAsm other  
288    = Just (text "requires via-C or native code generation (-fvia-C)")
289
290 checkCOrAsmOrInterp HscC           = Nothing
291 checkCOrAsmOrInterp HscAsm         = Nothing
292 checkCOrAsmOrInterp HscInterpreted = Nothing
293 checkCOrAsmOrInterp other  
294    = Just (text "requires interpreted, C or native code generation")
295
296 checkCOrAsmOrDotNet HscC   = Nothing
297 checkCOrAsmOrDotNet HscAsm = Nothing
298 checkCOrAsmOrDotNet HscILX = Nothing
299 checkCOrAsmOrDotNet other  
300    = Just (text "requires C, native or .NET ILX code generation")
301
302 checkCOrAsmOrDotNetOrInterp HscC           = Nothing
303 checkCOrAsmOrDotNetOrInterp HscAsm         = Nothing
304 checkCOrAsmOrDotNetOrInterp HscILX         = Nothing
305 checkCOrAsmOrDotNetOrInterp HscInterpreted = Nothing
306 checkCOrAsmOrDotNetOrInterp other  
307    = Just (text "requires interpreted, C, native or .NET ILX code generation")
308
309 checkCg check
310  = getDOpts             `thenM` \ dflags ->
311    let hscLang = dopt_HscLang dflags in
312    case hscLang of
313      HscNothing -> returnM ()
314      otherwise  ->
315        case check hscLang of
316          Nothing  -> returnM ()
317          Just err -> addErrTc (text "Illegal foreign declaration:" <+> err)
318 \end{code} 
319                            
320 Warnings
321
322 \begin{code}
323 check :: Bool -> Message -> TcM ()
324 check True _       = returnM ()
325 check _    the_err = addErrTc the_err
326
327 illegalForeignTyErr arg_or_res ty
328   = hang (hsep [ptext SLIT("Unacceptable"), arg_or_res, 
329                 ptext SLIT("type in foreign declaration:")])
330          4 (hsep [ppr ty])
331
332 -- Used for 'arg_or_res' argument to illegalForeignTyErr
333 argument = text "argument"
334 result   = text "result"
335
336 badCName :: CLabelString -> Message
337 badCName target 
338    = sep [quotes (ppr target) <+> ptext SLIT("is not a valid C identifier")]
339
340 foreignDeclCtxt fo
341   = hang (ptext SLIT("When checking declaration:"))
342          4 (ppr fo)
343 \end{code}
344