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 TcEnv ( newLocalName )
30 import TcMonoType ( tcHsSigType, UserTypeCtxt(..) )
31 import TcHsSyn ( TcMonoBinds, TypecheckedForeignDecl, TcForeignExportDecl )
32 import TcExpr ( tcExpr )
33 import Inst ( emptyLIE, LIE, plusLIE )
35 import ErrUtils ( Message )
36 import Id ( Id, mkLocalId, setIdLocalExported )
37 import PrimRep ( getPrimRepSize, isFloatingRep )
38 import Module ( Module )
39 import Type ( typePrimRep )
40 import OccName ( mkForeignExportOcc )
41 import Name ( Name(..), NamedThing(..), mkGlobalName )
42 import TcType ( Type, tcSplitFunTys, tcSplitTyConApp_maybe,
44 isFFIArgumentTy, isFFIImportResultTy,
45 isFFIExportResultTy, isFFILabelTy,
46 isFFIExternalTy, isFFIDynArgumentTy,
47 isFFIDynResultTy, isForeignPtrTy
49 import ForeignCall ( CCallSpec(..), CExportSpec(..), CCallTarget(..),
50 isDynamicTarget, isCasmTarget )
51 import CStrings ( CLabelString, isCLabelString )
52 import PrelNames ( hasKey, ioTyConKey )
53 import CmdLineOpts ( dopt_HscLang, HscLang(..) )
60 isForeignImport :: ForeignDecl name -> Bool
61 isForeignImport (ForeignImport _ _ _ _ _) = True
62 isForeignImport _ = False
65 isForeignExport :: ForeignDecl name -> Bool
66 isForeignExport (ForeignExport _ _ _ _ _) = True
67 isForeignExport _ = False
70 %************************************************************************
74 %************************************************************************
77 tcForeignImports :: [RenamedHsDecl] -> TcM ([Id], [TypecheckedForeignDecl])
78 tcForeignImports decls =
79 mapAndUnzipTc tcFImport
80 [ foreign_decl | ForD foreign_decl <- decls, isForeignImport foreign_decl]
82 tcFImport :: RenamedForeignDecl -> TcM (Id, TypecheckedForeignDecl)
83 tcFImport fo@(ForeignImport nm hs_ty imp_decl isDeprec src_loc)
84 = tcAddSrcLoc src_loc $
85 tcAddErrCtxt (foreignDeclCtxt fo) $
86 tcHsSigType (ForSigCtxt nm) hs_ty `thenTc` \ sig_ty ->
88 -- drop the foralls before inspecting the structure
89 -- of the foreign type.
90 (_, t_ty) = tcSplitForAllTys sig_ty
91 (arg_tys, res_ty) = tcSplitFunTys t_ty
92 id = mkLocalId nm sig_ty
94 tcCheckFIType sig_ty arg_tys res_ty imp_decl `thenNF_Tc_`
95 -- can't use sig_ty here because it :: Type and we need HsType Id
96 -- hence the undefined
97 returnTc (id, ForeignImport id undefined imp_decl isDeprec src_loc)
101 ------------ Checking types for foreign import ----------------------
103 tcCheckFIType _ _ _ (DNImport _)
104 = checkCg checkDotNet
106 tcCheckFIType sig_ty arg_tys res_ty (CImport _ _ _ _ (CLabel _))
107 = checkCg checkCOrAsm `thenNF_Tc_`
108 check (isFFILabelTy sig_ty) (illegalForeignTyErr empty sig_ty)
110 tcCheckFIType sig_ty arg_tys res_ty (CImport _ _ _ _ CWrapper)
111 = -- Foreign wrapper (former f.e.d.)
112 -- The type must be of the form ft -> IO (FunPtr ft), where ft is a
113 -- valid foreign type. For legacy reasons ft -> IO (Ptr ft) as well
114 -- as ft -> IO Addr is accepted, too. The use of the latter two forms
115 -- is DEPRECATED, though.
116 checkCg checkCOrAsmOrInterp `thenNF_Tc_`
118 [arg1_ty] -> checkForeignArgs isFFIExternalTy arg1_tys `thenNF_Tc_`
119 checkForeignRes nonIOok isFFIExportResultTy res1_ty `thenNF_Tc_`
120 checkForeignRes mustBeIO isFFIDynResultTy res_ty `thenNF_Tc_`
121 checkFEDArgs arg1_tys
123 (arg1_tys, res1_ty) = tcSplitFunTys arg1_ty
124 other -> addErrTc (illegalForeignTyErr empty sig_ty)
126 tcCheckFIType sig_ty arg_tys res_ty (CImport _ safety _ _ (CFunction target))
127 | isDynamicTarget target -- Foreign import dynamic
128 = checkCg checkCOrAsmOrInterp `thenNF_Tc_`
129 case arg_tys of -- The first arg must be Ptr, FunPtr, or Addr
130 [] -> check False (illegalForeignTyErr empty sig_ty)
131 (arg1_ty:arg_tys) -> getDOptsTc `thenNF_Tc` \ dflags ->
132 check (isFFIDynArgumentTy arg1_ty)
133 (illegalForeignTyErr argument arg1_ty) `thenNF_Tc_`
134 checkForeignArgs (isFFIArgumentTy dflags safety) arg_tys `thenNF_Tc_`
135 checkForeignRes nonIOok (isFFIImportResultTy dflags) res_ty
137 | otherwise -- Normal foreign import
138 = checkCg (if isCasmTarget target
139 then checkC else checkCOrAsmOrDotNetOrInterp) `thenNF_Tc_`
140 checkCTarget target `thenNF_Tc_`
141 getDOptsTc `thenNF_Tc` \ dflags ->
142 checkForeignArgs (isFFIArgumentTy dflags safety) arg_tys `thenNF_Tc_`
143 checkForeignRes nonIOok (isFFIImportResultTy dflags) res_ty
145 -- This makes a convenient place to check
146 -- that the C identifier is valid for C
147 checkCTarget (StaticTarget str)
148 = checkCg checkCOrAsmOrDotNetOrInterp `thenNF_Tc_`
149 check (isCLabelString str) (badCName str)
151 checkCTarget (CasmTarget _)
155 On a SPARC, with foreign export dynamic, due to a giant hack when building
156 adjustor thunks, we only allow 16 bytes of arguments!
158 So for example, args (Int,Double,Int) would be OK (1+2+1)
159 as would (Int,Int,Int,Int) (1+1+1+1) but not (Int,Double,Double) (1+2+2).
161 On an Alpha, due to a similar hack, we only allow 4 integer arguments with
162 foreign export dynamic (i.e., 32 bytes of arguments after padding each
163 argument to a quadword, excluding floating-point arguments).
165 The check is needed for both via-C and native-code routes
168 #include "nativeGen/NCG.h"
169 #if sparc_TARGET_ARCH
171 = check (words_of_args <= 4) err
173 words_of_args = sum (map (getPrimRepSize . typePrimRep) arg_tys)
174 err = ptext SLIT("On SPARC, I can only handle 4 words of arguments to foreign export dynamic")
176 #if alpha_TARGET_ARCH
178 = check (integral_args <= 4) err
180 integral_args = sum (map getPrimRepSize $
181 filter (not . isFloatingRep) $
182 map typePrimRep arg_tys)
183 err = ptext SLIT("On Alpha, I can only handle 4 non-floating-point arguments to foreign export dynamic")
185 checkFEDArgs arg_tys = returnNF_Tc ()
191 %************************************************************************
195 %************************************************************************
198 tcForeignExports :: Module -> [RenamedHsDecl]
199 -> TcM (LIE, TcMonoBinds, [TcForeignExportDecl])
200 tcForeignExports mod decls =
201 foldlTc combine (emptyLIE, EmptyMonoBinds, [])
202 [foreign_decl | ForD foreign_decl <- decls, isForeignExport foreign_decl]
204 combine (lie, binds, fs) fe =
205 tcFExport mod fe `thenTc ` \ (a_lie, b, f) ->
206 returnTc (lie `plusLIE` a_lie, b `AndMonoBinds` binds, f:fs)
208 tcFExport :: Module -> RenamedForeignDecl -> TcM (LIE, TcMonoBinds, TcForeignExportDecl)
209 tcFExport mod fo@(ForeignExport nm hs_ty spec isDeprec src_loc) =
210 tcAddSrcLoc src_loc $
211 tcAddErrCtxt (foreignDeclCtxt fo) $
213 tcHsSigType (ForSigCtxt nm) hs_ty `thenTc` \ sig_ty ->
214 tcExpr (HsVar nm) sig_ty `thenTc` \ (rhs, lie) ->
216 tcCheckFEType sig_ty spec `thenTc_`
218 -- we're exporting a function, but at a type possibly more
219 -- constrained than its declared/inferred type. Hence the need
220 -- to create a local binding which will call the exported function
221 -- at a particular type (and, maybe, overloading).
223 tcGetUnique `thenNF_Tc` \ uniq ->
225 gnm = mkGlobalName uniq mod (mkForeignExportOcc (getOccName nm)) src_loc
226 id = setIdLocalExported (mkLocalId gnm sig_ty)
227 bind = VarMonoBind id rhs
229 returnTc (lie, bind, ForeignExport id undefined spec isDeprec src_loc)
232 ------------ Checking argument types for foreign export ----------------------
235 tcCheckFEType sig_ty (CExport (CExportStatic str _))
236 = check (isCLabelString str) (badCName str) `thenNF_Tc_`
237 checkForeignArgs isFFIExternalTy arg_tys `thenNF_Tc_`
238 checkForeignRes nonIOok isFFIExportResultTy res_ty
240 -- Drop the foralls before inspecting n
241 -- the structure of the foreign type.
242 (_, t_ty) = tcSplitForAllTys sig_ty
243 (arg_tys, res_ty) = tcSplitFunTys t_ty
248 %************************************************************************
250 \subsection{Miscellaneous}
252 %************************************************************************
255 ------------ Checking argument types for foreign import ----------------------
256 checkForeignArgs :: (Type -> Bool) -> [Type] -> NF_TcM ()
257 checkForeignArgs pred tys
258 = mapNF_Tc go tys `thenNF_Tc_`
261 go ty = check (pred ty) (illegalForeignTyErr argument ty) `thenNF_Tc_`
262 warnTc (isForeignPtrTy ty) foreignPtrWarn
265 text "`ForeignPtr' as argument type in a foreign import is deprecated"
267 ------------ Checking result types for foreign calls ----------------------
268 -- Check that the type has the form
269 -- (IO t) or (t) , and that t satisfies the given predicate.
271 checkForeignRes :: Bool -> (Type -> Bool) -> Type -> NF_TcM ()
276 checkForeignRes non_io_result_ok pred_res_ty ty
277 = case tcSplitTyConApp_maybe ty of
279 | io `hasKey` ioTyConKey && pred_res_ty res_ty
282 -> check (non_io_result_ok && pred_res_ty ty)
283 (illegalForeignTyErr result ty)
287 checkDotNet HscILX = Nothing
288 checkDotNet other = Just (text "requires .NET code generation (-filx)")
290 checkC HscC = Nothing
291 checkC other = Just (text "requires C code generation (-fvia-C)")
293 checkCOrAsm HscC = Nothing
294 checkCOrAsm HscAsm = Nothing
296 = Just (text "requires via-C or native code generation (-fvia-C)")
298 checkCOrAsmOrInterp HscC = Nothing
299 checkCOrAsmOrInterp HscAsm = Nothing
300 checkCOrAsmOrInterp HscInterpreted = Nothing
301 checkCOrAsmOrInterp other
302 = Just (text "requires interpreted, C or native code generation")
304 checkCOrAsmOrDotNet HscC = Nothing
305 checkCOrAsmOrDotNet HscAsm = Nothing
306 checkCOrAsmOrDotNet HscILX = Nothing
307 checkCOrAsmOrDotNet other
308 = Just (text "requires C, native or .NET ILX code generation")
310 checkCOrAsmOrDotNetOrInterp HscC = Nothing
311 checkCOrAsmOrDotNetOrInterp HscAsm = Nothing
312 checkCOrAsmOrDotNetOrInterp HscILX = Nothing
313 checkCOrAsmOrDotNetOrInterp HscInterpreted = Nothing
314 checkCOrAsmOrDotNetOrInterp other
315 = Just (text "requires interpreted, C, native or .NET ILX code generation")
318 = getDOptsTc `thenNF_Tc` \ dflags ->
319 let hscLang = dopt_HscLang dflags in
321 HscNothing -> returnNF_Tc ()
323 case check hscLang of
324 Nothing -> returnNF_Tc ()
325 Just err -> addErrTc (text "Illegal foreign declaration:" <+> err)
331 check :: Bool -> Message -> NF_TcM ()
332 check True _ = returnTc ()
333 check _ the_err = addErrTc the_err
335 illegalForeignTyErr arg_or_res ty
336 = hang (hsep [ptext SLIT("Unacceptable"), arg_or_res,
337 ptext SLIT("type in foreign declaration:")])
340 -- Used for 'arg_or_res' argument to illegalForeignTyErr
341 argument = text "argument"
342 result = text "result"
344 badCName :: CLabelString -> Message
346 = sep [quotes (ppr target) <+> ptext SLIT("is not a valid C identifier")]
349 = hang (ptext SLIT("When checking declaration:"))