2 % (c) The AQUA Project, Glasgow University, 1998
4 \section[TcForeign]{Typechecking \tr{foreign} declarations}
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.
20 #include "HsVersions.h"
22 import HsSyn ( HsDecl(..), ForeignDecl(..), HsExpr(..),
23 MonoBinds(..), ForeignImport(..), ForeignExport(..),
26 import RnHsSyn ( RenamedHsDecl, RenamedForeignDecl )
29 import TcMonoType ( tcHsSigType, UserTypeCtxt(..) )
30 import TcHsSyn ( TcMonoBinds, TypecheckedForeignDecl, TcForeignExportDecl )
31 import TcExpr ( tcExpr )
32 import Inst ( emptyLIE, LIE, plusLIE )
34 import ErrUtils ( Message )
35 import Id ( Id, mkLocalId, setIdLocalExported )
36 import PrimRep ( getPrimRepSize, isFloatingRep )
37 import Module ( Module )
38 import Type ( typePrimRep )
39 import OccName ( mkForeignExportOcc )
40 import Name ( NamedThing(..), mkExternalName )
41 import TcType ( Type, tcSplitFunTys, tcSplitTyConApp_maybe,
43 isFFIArgumentTy, isFFIImportResultTy,
44 isFFIExportResultTy, isFFILabelTy,
45 isFFIExternalTy, isFFIDynArgumentTy,
46 isFFIDynResultTy, isForeignPtrTy
48 import ForeignCall ( CExportSpec(..), CCallTarget(..),
49 isDynamicTarget, isCasmTarget )
50 import CStrings ( CLabelString, isCLabelString )
51 import PrelNames ( hasKey, ioTyConKey )
52 import CmdLineOpts ( dopt_HscLang, HscLang(..) )
59 isForeignImport :: ForeignDecl name -> Bool
60 isForeignImport (ForeignImport _ _ _ _ _) = True
61 isForeignImport _ = False
64 isForeignExport :: ForeignDecl name -> Bool
65 isForeignExport (ForeignExport _ _ _ _ _) = True
66 isForeignExport _ = False
69 %************************************************************************
73 %************************************************************************
76 tcForeignImports :: [RenamedHsDecl] -> TcM ([Id], [TypecheckedForeignDecl])
77 tcForeignImports decls =
78 mapAndUnzipTc tcFImport
79 [ foreign_decl | ForD foreign_decl <- decls, isForeignImport foreign_decl]
81 tcFImport :: RenamedForeignDecl -> TcM (Id, TypecheckedForeignDecl)
82 tcFImport fo@(ForeignImport nm hs_ty imp_decl isDeprec src_loc)
83 = tcAddSrcLoc src_loc $
84 tcAddErrCtxt (foreignDeclCtxt fo) $
85 tcHsSigType (ForSigCtxt nm) hs_ty `thenTc` \ sig_ty ->
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
93 tcCheckFIType sig_ty arg_tys res_ty imp_decl `thenNF_Tc_`
94 -- can't use sig_ty here because it :: Type and we need HsType Id
95 -- hence the undefined
96 returnTc (id, ForeignImport id undefined imp_decl isDeprec src_loc)
100 ------------ Checking types for foreign import ----------------------
102 tcCheckFIType _ _ _ (DNImport _)
103 = checkCg checkDotNet
105 tcCheckFIType sig_ty arg_tys res_ty (CImport _ _ _ _ (CLabel _))
106 = checkCg checkCOrAsm `thenNF_Tc_`
107 check (isFFILabelTy sig_ty) (illegalForeignTyErr empty sig_ty)
109 tcCheckFIType sig_ty arg_tys res_ty (CImport _ _ _ _ CWrapper)
110 = -- Foreign wrapper (former f.e.d.)
111 -- The type must be of the form ft -> IO (FunPtr ft), where ft is a
112 -- valid foreign type. For legacy reasons ft -> IO (Ptr ft) as well
113 -- as ft -> IO Addr is accepted, too. The use of the latter two forms
114 -- is DEPRECATED, though.
115 checkCg checkCOrAsmOrInterp `thenNF_Tc_`
117 [arg1_ty] -> checkForeignArgs isFFIExternalTy arg1_tys `thenNF_Tc_`
118 checkForeignRes nonIOok isFFIExportResultTy res1_ty `thenNF_Tc_`
119 checkForeignRes mustBeIO isFFIDynResultTy res_ty `thenNF_Tc_`
120 checkFEDArgs arg1_tys
122 (arg1_tys, res1_ty) = tcSplitFunTys arg1_ty
123 other -> addErrTc (illegalForeignTyErr empty sig_ty)
125 tcCheckFIType sig_ty arg_tys res_ty (CImport _ safety _ _ (CFunction target))
126 | isDynamicTarget target -- Foreign import dynamic
127 = checkCg checkCOrAsmOrInterp `thenNF_Tc_`
128 case arg_tys of -- The first arg must be Ptr, FunPtr, or Addr
129 [] -> check False (illegalForeignTyErr empty sig_ty)
130 (arg1_ty:arg_tys) -> getDOptsTc `thenNF_Tc` \ dflags ->
131 check (isFFIDynArgumentTy arg1_ty)
132 (illegalForeignTyErr argument arg1_ty) `thenNF_Tc_`
133 checkForeignArgs (isFFIArgumentTy dflags safety) arg_tys `thenNF_Tc_`
134 checkForeignRes nonIOok (isFFIImportResultTy dflags) res_ty
136 | otherwise -- Normal foreign import
137 = checkCg (if isCasmTarget target
138 then checkC else checkCOrAsmOrDotNetOrInterp) `thenNF_Tc_`
139 checkCTarget target `thenNF_Tc_`
140 getDOptsTc `thenNF_Tc` \ dflags ->
141 checkForeignArgs (isFFIArgumentTy dflags safety) arg_tys `thenNF_Tc_`
142 checkForeignRes nonIOok (isFFIImportResultTy dflags) res_ty
144 -- This makes a convenient place to check
145 -- that the C identifier is valid for C
146 checkCTarget (StaticTarget str)
147 = checkCg checkCOrAsmOrDotNetOrInterp `thenNF_Tc_`
148 check (isCLabelString str) (badCName str)
150 checkCTarget (CasmTarget _)
154 On a SPARC, with foreign export dynamic, due to a giant hack when building
155 adjustor thunks, we only allow 16 bytes of arguments!
157 So for example, args (Int,Double,Int) would be OK (1+2+1)
158 as would (Int,Int,Int,Int) (1+1+1+1) but not (Int,Double,Double) (1+2+2).
160 On an Alpha, due to a similar hack, we only allow 4 integer arguments with
161 foreign export dynamic (i.e., 32 bytes of arguments after padding each
162 argument to a quadword, excluding floating-point arguments).
164 The check is needed for both via-C and native-code routes
167 #include "nativeGen/NCG.h"
168 #if sparc_TARGET_ARCH
170 = check (words_of_args <= 4) err
172 words_of_args = sum (map (getPrimRepSize . typePrimRep) arg_tys)
173 err = ptext SLIT("On SPARC, I can only handle 4 words of arguments to foreign export dynamic")
175 #if alpha_TARGET_ARCH
177 = check (integral_args <= 4) err
179 integral_args = sum (map getPrimRepSize $
180 filter (not . isFloatingRep) $
181 map typePrimRep arg_tys)
182 err = ptext SLIT("On Alpha, I can only handle 4 non-floating-point arguments to foreign export dynamic")
184 checkFEDArgs arg_tys = returnNF_Tc ()
190 %************************************************************************
194 %************************************************************************
197 tcForeignExports :: Module -> [RenamedHsDecl]
198 -> TcM (LIE, TcMonoBinds, [TcForeignExportDecl])
199 tcForeignExports mod decls =
200 foldlTc combine (emptyLIE, EmptyMonoBinds, [])
201 [foreign_decl | ForD foreign_decl <- decls, isForeignExport foreign_decl]
203 combine (lie, binds, fs) fe =
204 tcFExport mod fe `thenTc ` \ (a_lie, b, f) ->
205 returnTc (lie `plusLIE` a_lie, b `AndMonoBinds` binds, f:fs)
207 tcFExport :: Module -> RenamedForeignDecl -> TcM (LIE, TcMonoBinds, TcForeignExportDecl)
208 tcFExport mod fo@(ForeignExport nm hs_ty spec isDeprec src_loc) =
209 tcAddSrcLoc src_loc $
210 tcAddErrCtxt (foreignDeclCtxt fo) $
212 tcHsSigType (ForSigCtxt nm) hs_ty `thenTc` \ sig_ty ->
213 tcExpr (HsVar nm) sig_ty `thenTc` \ (rhs, lie) ->
215 tcCheckFEType sig_ty spec `thenTc_`
217 -- we're exporting a function, but at a type possibly more
218 -- constrained than its declared/inferred type. Hence the need
219 -- to create a local binding which will call the exported function
220 -- at a particular type (and, maybe, overloading).
222 tcGetUnique `thenNF_Tc` \ uniq ->
224 gnm = mkExternalName uniq mod (mkForeignExportOcc (getOccName nm)) src_loc
225 id = setIdLocalExported (mkLocalId gnm sig_ty)
226 bind = VarMonoBind id rhs
228 returnTc (lie, bind, ForeignExport id undefined spec isDeprec src_loc)
231 ------------ Checking argument types for foreign export ----------------------
234 tcCheckFEType sig_ty (CExport (CExportStatic str _))
235 = check (isCLabelString str) (badCName str) `thenNF_Tc_`
236 checkForeignArgs isFFIExternalTy arg_tys `thenNF_Tc_`
237 checkForeignRes nonIOok isFFIExportResultTy res_ty
239 -- Drop the foralls before inspecting n
240 -- the structure of the foreign type.
241 (_, t_ty) = tcSplitForAllTys sig_ty
242 (arg_tys, res_ty) = tcSplitFunTys t_ty
247 %************************************************************************
249 \subsection{Miscellaneous}
251 %************************************************************************
254 ------------ Checking argument types for foreign import ----------------------
255 checkForeignArgs :: (Type -> Bool) -> [Type] -> NF_TcM ()
256 checkForeignArgs pred tys
257 = mapNF_Tc go tys `thenNF_Tc_`
260 go ty = check (pred ty) (illegalForeignTyErr argument ty) `thenNF_Tc_`
261 warnTc (isForeignPtrTy ty) foreignPtrWarn
264 text "`ForeignPtr' as argument type in a foreign import is deprecated"
266 ------------ Checking result types for foreign calls ----------------------
267 -- Check that the type has the form
268 -- (IO t) or (t) , and that t satisfies the given predicate.
270 checkForeignRes :: Bool -> (Type -> Bool) -> Type -> NF_TcM ()
275 checkForeignRes non_io_result_ok pred_res_ty ty
276 = case tcSplitTyConApp_maybe ty of
278 | io `hasKey` ioTyConKey && pred_res_ty res_ty
281 -> check (non_io_result_ok && pred_res_ty ty)
282 (illegalForeignTyErr result ty)
286 checkDotNet HscILX = Nothing
287 checkDotNet other = Just (text "requires .NET code generation (-filx)")
289 checkC HscC = Nothing
290 checkC other = Just (text "requires C code generation (-fvia-C)")
292 checkCOrAsm HscC = Nothing
293 checkCOrAsm HscAsm = Nothing
295 = Just (text "requires via-C or native code generation (-fvia-C)")
297 checkCOrAsmOrInterp HscC = Nothing
298 checkCOrAsmOrInterp HscAsm = Nothing
299 checkCOrAsmOrInterp HscInterpreted = Nothing
300 checkCOrAsmOrInterp other
301 = Just (text "requires interpreted, C or native code generation")
303 checkCOrAsmOrDotNet HscC = Nothing
304 checkCOrAsmOrDotNet HscAsm = Nothing
305 checkCOrAsmOrDotNet HscILX = Nothing
306 checkCOrAsmOrDotNet other
307 = Just (text "requires C, native or .NET ILX code generation")
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")
317 = getDOptsTc `thenNF_Tc` \ dflags ->
318 let hscLang = dopt_HscLang dflags in
320 HscNothing -> returnNF_Tc ()
322 case check hscLang of
323 Nothing -> returnNF_Tc ()
324 Just err -> addErrTc (text "Illegal foreign declaration:" <+> err)
330 check :: Bool -> Message -> NF_TcM ()
331 check True _ = returnTc ()
332 check _ the_err = addErrTc the_err
334 illegalForeignTyErr arg_or_res ty
335 = hang (hsep [ptext SLIT("Unacceptable"), arg_or_res,
336 ptext SLIT("type in foreign declaration:")])
339 -- Used for 'arg_or_res' argument to illegalForeignTyErr
340 argument = text "argument"
341 result = text "result"
343 badCName :: CLabelString -> Message
345 = sep [quotes (ppr target) <+> ptext SLIT("is not a valid C identifier")]
348 = hang (ptext SLIT("When checking declaration:"))