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 )
37 import Name ( nameOccName )
38 import PrimRep ( getPrimRepSize, isFloatingRep )
39 import Type ( typePrimRep )
40 import TcType ( Type, tcSplitFunTys, tcSplitTyConApp_maybe,
42 isFFIArgumentTy, isFFIImportResultTy,
43 isFFIExportResultTy, isFFILabelTy,
44 isFFIExternalTy, isFFIDynArgumentTy,
45 isFFIDynResultTy, isForeignPtrTy
47 import ForeignCall ( CCallSpec(..), CExportSpec(..), CCallTarget(..),
48 isDynamicTarget, isCasmTarget )
49 import CStrings ( CLabelString, isCLabelString )
50 import PrelNames ( hasKey, ioTyConKey )
51 import CmdLineOpts ( dopt_HscLang, HscLang(..) )
58 isForeignImport :: ForeignDecl name -> Bool
59 isForeignImport (ForeignImport _ _ _ _ _) = True
60 isForeignImport _ = False
63 isForeignExport :: ForeignDecl name -> Bool
64 isForeignExport (ForeignExport _ _ _ _ _) = True
65 isForeignExport _ = False
68 %************************************************************************
72 %************************************************************************
75 tcForeignImports :: [RenamedHsDecl] -> TcM ([Id], [TypecheckedForeignDecl])
76 tcForeignImports decls =
77 mapAndUnzipTc tcFImport
78 [ foreign_decl | ForD foreign_decl <- decls, isForeignImport foreign_decl]
80 tcFImport :: RenamedForeignDecl -> TcM (Id, TypecheckedForeignDecl)
81 tcFImport fo@(ForeignImport nm hs_ty imp_decl isDeprec src_loc)
82 = tcAddSrcLoc src_loc $
83 tcAddErrCtxt (foreignDeclCtxt fo) $
84 tcHsSigType (ForSigCtxt nm) hs_ty `thenTc` \ sig_ty ->
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
92 tcCheckFIType sig_ty arg_tys res_ty imp_decl `thenNF_Tc_`
93 returnTc (id, ForeignImport id undefined imp_decl isDeprec src_loc)
97 ------------ Checking types for foreign import ----------------------
99 tcCheckFIType _ _ _ (DNImport _)
100 = checkCg checkDotNet
102 tcCheckFIType sig_ty arg_tys res_ty (CImport _ _ _ _ (CLabel _))
103 = checkCg checkCOrAsm `thenNF_Tc_`
104 check (isFFILabelTy sig_ty) (illegalForeignTyErr empty sig_ty)
106 tcCheckFIType sig_ty arg_tys res_ty (CImport _ _ _ _ CWrapper)
107 = -- Foreign wrapper (former f.e.d.)
108 -- The type must be of the form ft -> IO (FunPtr ft), where ft is a
109 -- valid foreign type. For legacy reasons ft -> IO (Ptr ft) as well
110 -- as ft -> IO Addr is accepted, too. The use of the latter two forms
111 -- is DEPRECATED, though.
112 checkCg checkCOrAsm `thenNF_Tc_`
114 [arg1_ty] -> checkForeignArgs isFFIExternalTy arg1_tys `thenNF_Tc_`
115 checkForeignRes nonIOok isFFIExportResultTy res1_ty `thenNF_Tc_`
116 checkForeignRes mustBeIO isFFIDynResultTy res_ty `thenNF_Tc_`
117 checkFEDArgs arg1_tys
119 (arg1_tys, res1_ty) = tcSplitFunTys arg1_ty
120 other -> addErrTc (illegalForeignTyErr empty sig_ty)
122 tcCheckFIType sig_ty arg_tys res_ty (CImport _ safety _ _ (CFunction target))
123 | isDynamicTarget target -- Foreign import dynamic
124 = checkCg checkCOrAsmOrInterp `thenNF_Tc_`
125 case arg_tys of -- The first arg must be Ptr, FunPtr, or Addr
126 [] -> check False (illegalForeignTyErr empty sig_ty)
127 (arg1_ty:arg_tys) -> getDOptsTc `thenNF_Tc` \ dflags ->
128 check (isFFIDynArgumentTy arg1_ty)
129 (illegalForeignTyErr argument arg1_ty) `thenNF_Tc_`
130 checkForeignArgs (isFFIArgumentTy dflags safety) arg_tys `thenNF_Tc_`
131 checkForeignRes nonIOok (isFFIImportResultTy dflags) res_ty
133 | otherwise -- Normal foreign import
134 = checkCg (if isCasmTarget target
135 then checkC else checkCOrAsmOrDotNetOrInterp) `thenNF_Tc_`
136 checkCTarget target `thenNF_Tc_`
137 getDOptsTc `thenNF_Tc` \ dflags ->
138 checkForeignArgs (isFFIArgumentTy dflags safety) arg_tys `thenNF_Tc_`
139 checkForeignRes nonIOok (isFFIImportResultTy dflags) res_ty
141 -- This makes a convenient place to check
142 -- that the C identifier is valid for C
143 checkCTarget (StaticTarget str)
144 = checkCg checkCOrAsmOrDotNetOrInterp `thenNF_Tc_`
145 check (isCLabelString str) (badCName str)
147 checkCTarget (CasmTarget _)
151 On a SPARC, with foreign export dynamic, due to a giant hack when building
152 adjustor thunks, we only allow 16 bytes of arguments!
154 So for example, args (Int,Double,Int) would be OK (1+2+1)
155 as would (Int,Int,Int,Int) (1+1+1+1) but not (Int,Double,Double) (1+2+2).
157 On an Alpha, due to a similar hack, we only allow 4 integer arguments with
158 foreign export dynamic (i.e., 32 bytes of arguments after padding each
159 argument to a quadword, excluding floating-point arguments).
161 The check is needed for both via-C and native-code routes
164 #include "nativeGen/NCG.h"
165 #if sparc_TARGET_ARCH
167 = check (words_of_args <= 4) err
169 words_of_args = sum (map (getPrimRepSize . typePrimRep) arg_tys)
170 err = ptext SLIT("On SPARC, I can only handle 4 words of arguments to foreign export dynamic")
172 #if alpha_TARGET_ARCH
174 = check (integral_args <= 4) err
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")
181 checkFEDArgs arg_tys = returnNF_Tc ()
187 %************************************************************************
191 %************************************************************************
194 tcForeignExports :: [RenamedHsDecl] -> TcM (LIE, TcMonoBinds, [TcForeignExportDecl])
195 tcForeignExports decls =
196 foldlTc combine (emptyLIE, EmptyMonoBinds, [])
197 [foreign_decl | ForD foreign_decl <- decls, isForeignExport foreign_decl]
199 combine (lie, binds, fs) fe =
200 tcFExport fe `thenTc ` \ (a_lie, b, f) ->
201 returnTc (lie `plusLIE` a_lie, b `AndMonoBinds` binds, f:fs)
203 tcFExport :: RenamedForeignDecl -> TcM (LIE, TcMonoBinds, TcForeignExportDecl)
204 tcFExport fo@(ForeignExport nm hs_ty spec isDeprec src_loc) =
205 tcAddSrcLoc src_loc $
206 tcAddErrCtxt (foreignDeclCtxt fo) $
208 tcHsSigType (ForSigCtxt nm) hs_ty `thenTc` \ sig_ty ->
209 tcExpr (HsVar nm) sig_ty `thenTc` \ (rhs, lie) ->
211 tcCheckFEType sig_ty spec `thenTc_`
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 newLocalName nm `thenNF_Tc` \ id_name ->
219 id = mkLocalId id_name sig_ty
220 bind = VarMonoBind id rhs
222 returnTc (lie, bind, ForeignExport id undefined spec isDeprec src_loc)
225 ------------ Checking argument types for foreign export ----------------------
228 tcCheckFEType sig_ty (CExport (CExportStatic str _))
229 = check (isCLabelString str) (badCName str) `thenNF_Tc_`
230 checkForeignArgs isFFIExternalTy arg_tys `thenNF_Tc_`
231 checkForeignRes nonIOok isFFIExportResultTy res_ty
233 -- Drop the foralls before inspecting n
234 -- the structure of the foreign type.
235 (_, t_ty) = tcSplitForAllTys sig_ty
236 (arg_tys, res_ty) = tcSplitFunTys t_ty
241 %************************************************************************
243 \subsection{Miscellaneous}
245 %************************************************************************
248 ------------ Checking argument types for foreign import ----------------------
249 checkForeignArgs :: (Type -> Bool) -> [Type] -> NF_TcM ()
250 checkForeignArgs pred tys
251 = mapNF_Tc go tys `thenNF_Tc_`
254 go ty = check (pred ty) (illegalForeignTyErr argument ty) `thenNF_Tc_`
255 warnTc (isForeignPtrTy ty) foreignPtrWarn
258 text "`ForeignPtr' as argument type in a foreign import is deprecated"
260 ------------ Checking result types for foreign calls ----------------------
261 -- Check that the type has the form
262 -- (IO t) or (t) , and that t satisfies the given predicate.
264 checkForeignRes :: Bool -> (Type -> Bool) -> Type -> NF_TcM ()
269 checkForeignRes non_io_result_ok pred_res_ty ty
270 = case tcSplitTyConApp_maybe ty of
272 | io `hasKey` ioTyConKey && pred_res_ty res_ty
275 -> check (non_io_result_ok && pred_res_ty ty)
276 (illegalForeignTyErr result ty)
280 checkDotNet HscILX = Nothing
281 checkDotNet other = Just (text "requires .NET code generation (-filx)")
283 checkC HscC = Nothing
284 checkC other = Just (text "requires C code generation (-fvia-C)")
286 checkCOrAsm HscC = Nothing
287 checkCOrAsm HscAsm = Nothing
289 = Just (text "requires via-C or native code generation (-fvia-C)")
291 checkCOrAsmOrInterp HscC = Nothing
292 checkCOrAsmOrInterp HscAsm = Nothing
293 checkCOrAsmOrInterp HscInterpreted = Nothing
294 checkCOrAsmOrInterp other
295 = Just (text "requires interpreted, C or native code generation")
297 checkCOrAsmOrDotNet HscC = Nothing
298 checkCOrAsmOrDotNet HscAsm = Nothing
299 checkCOrAsmOrDotNet HscILX = Nothing
300 checkCOrAsmOrDotNet other
301 = Just (text "requires C, native or .NET ILX code generation")
303 checkCOrAsmOrDotNetOrInterp HscC = Nothing
304 checkCOrAsmOrDotNetOrInterp HscAsm = Nothing
305 checkCOrAsmOrDotNetOrInterp HscILX = Nothing
306 checkCOrAsmOrDotNetOrInterp HscInterpreted = Nothing
307 checkCOrAsmOrDotNetOrInterp other
308 = Just (text "requires interpreted, C, native or .NET ILX code generation")
311 = getDOptsTc `thenNF_Tc` \ dflags ->
312 let hscLang = dopt_HscLang dflags in
314 HscNothing -> returnNF_Tc ()
316 case check hscLang of
317 Nothing -> returnNF_Tc ()
318 Just err -> addErrTc (text "Illegal foreign declaration:" <+> err)
324 check :: Bool -> Message -> NF_TcM ()
325 check True _ = returnTc ()
326 check _ the_err = addErrTc the_err
328 illegalForeignTyErr arg_or_res ty
329 = hang (hsep [ptext SLIT("Unacceptable"), arg_or_res,
330 ptext SLIT("type in foreign declaration:")])
333 -- Used for 'arg_or_res' argument to illegalForeignTyErr
334 argument = text "argument"
335 result = text "result"
337 badCName :: CLabelString -> Message
339 = sep [quotes (ppr target) <+> ptext SLIT("is not a valid C identifier")]
342 = hang (ptext SLIT("When checking declaration:"))