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(..), FoImport(..), FoExport(..)
25 import RnHsSyn ( RenamedHsDecl, RenamedForeignDecl )
28 import TcEnv ( newLocalName )
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 )
36 import Name ( nameOccName )
37 import PrimRep ( getPrimRepSize, isFloatingRep )
38 import Type ( typePrimRep )
39 import TcType ( Type, tcSplitFunTys, tcSplitTyConApp_maybe, tcSplitForAllTys,
40 isFFIArgumentTy, isFFIImportResultTy,
41 isFFIExportResultTy, isFFILabelTy,
42 isFFIExternalTy, isFFIDynArgumentTy, isFFIDynResultTy
44 import ForeignCall ( CCallSpec(..), CExportSpec(..), CCallTarget(..), isDynamicTarget, isCasmTarget )
45 import CStrings ( CLabelString, isCLabelString )
46 import PrelNames ( hasKey, ioTyConKey )
47 import CmdLineOpts ( dopt_HscLang, HscLang(..) )
54 isForeignImport :: ForeignDecl name -> Bool
55 isForeignImport (ForeignImport _ _ _ _) = True
56 isForeignImport _ = False
59 isForeignExport :: ForeignDecl name -> Bool
60 isForeignExport (ForeignExport _ _ _ _) = True
61 isForeignExport _ = False
64 %************************************************************************
68 %************************************************************************
71 tcForeignImports :: [RenamedHsDecl] -> TcM ([Id], [TypecheckedForeignDecl])
72 tcForeignImports decls =
73 mapAndUnzipTc tcFImport [ foreign_decl | ForD foreign_decl <- decls, isForeignImport foreign_decl]
75 tcFImport :: RenamedForeignDecl -> TcM (Id, TypecheckedForeignDecl)
76 tcFImport fo@(ForeignImport nm hs_ty imp_decl src_loc)
77 = tcAddSrcLoc src_loc $
78 tcAddErrCtxt (foreignDeclCtxt fo) $
79 tcHsSigType (ForSigCtxt nm) hs_ty `thenTc` \ sig_ty ->
81 -- drop the foralls before inspecting the structure
82 -- of the foreign type.
83 (_, t_ty) = tcSplitForAllTys sig_ty
84 (arg_tys, res_ty) = tcSplitFunTys t_ty
85 id = mkLocalId nm sig_ty
87 tcCheckFIType sig_ty arg_tys res_ty imp_decl `thenNF_Tc_`
88 returnTc (id, ForeignImport id undefined imp_decl src_loc)
92 ------------ Checking types for foreign import ----------------------
94 tcCheckFIType _ _ _ (DNImport _)
97 tcCheckFIType sig_ty arg_tys res_ty (LblImport _)
98 = checkCg checkCOrAsm `thenNF_Tc_`
99 check (isFFILabelTy sig_ty) (illegalForeignTyErr empty sig_ty)
101 tcCheckFIType sig_ty arg_tys res_ty (CDynImport _)
102 = -- Foreign export dynamic
103 -- The first (and only!) arg has got to be a function type
104 -- and it must return IO t; result type is IO Addr
105 checkCg checkCOrAsm `thenNF_Tc_`
107 [arg1_ty] -> checkForeignArgs isFFIExternalTy arg1_tys `thenNF_Tc_`
108 checkForeignRes nonIOok isFFIExportResultTy res1_ty `thenNF_Tc_`
109 checkForeignRes mustBeIO isFFIDynResultTy res_ty `thenNF_Tc_`
110 checkFEDArgs arg1_tys
112 (arg1_tys, res1_ty) = tcSplitFunTys arg1_ty
113 other -> addErrTc (illegalForeignTyErr empty sig_ty)
115 tcCheckFIType sig_ty arg_tys res_ty (CImport (CCallSpec target _ safety))
116 | isDynamicTarget target -- Foreign import dynamic
117 = checkCg checkCOrAsmOrInterp `thenNF_Tc_`
118 case arg_tys of -- The first arg must be Addr
119 [] -> check False (illegalForeignTyErr empty sig_ty)
120 (arg1_ty:arg_tys) -> getDOptsTc `thenNF_Tc` \ dflags ->
121 check (isFFIDynArgumentTy arg1_ty)
122 (illegalForeignTyErr argument arg1_ty) `thenNF_Tc_`
123 checkForeignArgs (isFFIArgumentTy dflags safety) arg_tys `thenNF_Tc_`
124 checkForeignRes nonIOok (isFFIImportResultTy dflags) res_ty
126 | otherwise -- Normal foreign import
127 = checkCg (if isCasmTarget target
128 then checkC else checkCOrAsmOrDotNetOrInterp) `thenNF_Tc_`
129 checkCTarget target `thenNF_Tc_`
130 getDOptsTc `thenNF_Tc` \ dflags ->
131 checkForeignArgs (isFFIArgumentTy dflags safety) arg_tys `thenNF_Tc_`
132 checkForeignRes nonIOok (isFFIImportResultTy dflags) res_ty
134 -- This makes a convenient place to check
135 -- that the C identifier is valid for C
136 checkCTarget (StaticTarget str)
137 = checkCg checkCOrAsmOrDotNetOrInterp `thenNF_Tc_`
138 check (isCLabelString str) (badCName str)
140 checkCTarget (CasmTarget _)
144 On a SPARC, with foreign export dynamic, due to a giant hack when building
145 adjustor thunks, we only allow 16 bytes of arguments!
147 So for example, args (Int,Double,Int) would be OK (1+2+1)
148 as would (Int,Int,Int,Int) (1+1+1+1) but not (Int,Double,Double) (1+2+2).
150 On an Alpha, due to a similar hack, we only allow 4 integer arguments with
151 foreign export dynamic (i.e., 32 bytes of arguments after padding each
152 argument to a quadword, excluding floating-point arguments).
154 The check is needed for both via-C and native-code routes
157 #include "nativeGen/NCG.h"
158 #if sparc_TARGET_ARCH
160 = check (words_of_args <= 4) err
162 words_of_args = sum (map (getPrimRepSize . typePrimRep) arg_tys)
163 err = ptext SLIT("On SPARC, I can only handle 4 words of arguments to foreign export dynamic")
165 #if alpha_TARGET_ARCH
167 = check (integral_args <= 4) err
169 integral_args = sum (map getPrimRepSize $
170 filter (not . isFloatingRep) $
171 map typePrimRep arg_tys)
172 err = ptext SLIT("On Alpha, I can only handle 4 non-floating-point arguments to foreign export dynamic")
174 checkFEDArgs arg_tys = returnNF_Tc ()
180 %************************************************************************
184 %************************************************************************
187 tcForeignExports :: [RenamedHsDecl] -> TcM (LIE, TcMonoBinds, [TcForeignExportDecl])
188 tcForeignExports decls =
189 foldlTc combine (emptyLIE, EmptyMonoBinds, [])
190 [ foreign_decl | ForD foreign_decl <- decls, isForeignExport foreign_decl]
192 combine (lie, binds, fs) fe =
193 tcFExport fe `thenTc ` \ (a_lie, b, f) ->
194 returnTc (lie `plusLIE` a_lie, b `AndMonoBinds` binds, f:fs)
196 tcFExport :: RenamedForeignDecl -> TcM (LIE, TcMonoBinds, TcForeignExportDecl)
197 tcFExport fo@(ForeignExport nm hs_ty spec src_loc) =
198 tcAddSrcLoc src_loc $
199 tcAddErrCtxt (foreignDeclCtxt fo) $
201 tcHsSigType (ForSigCtxt nm) hs_ty `thenTc` \ sig_ty ->
202 tcExpr (HsVar nm) sig_ty `thenTc` \ (rhs, lie) ->
204 tcCheckFEType sig_ty spec `thenTc_`
206 -- we're exporting a function, but at a type possibly more constrained
207 -- than its declared/inferred type. Hence the need
208 -- to create a local binding which will call the exported function
209 -- at a particular type (and, maybe, overloading).
210 newLocalName nm `thenNF_Tc` \ id_name ->
212 id = mkLocalId id_name sig_ty
213 bind = VarMonoBind id rhs
215 returnTc (lie, bind, ForeignExport id undefined spec src_loc)
218 ------------ Checking argument types for foreign export ----------------------
221 tcCheckFEType sig_ty (CExport (CExportStatic str _))
222 = check (isCLabelString str) (badCName str) `thenNF_Tc_`
223 checkForeignArgs isFFIExternalTy arg_tys `thenNF_Tc_`
224 checkForeignRes nonIOok isFFIExportResultTy res_ty
226 -- Drop the foralls before inspecting n
227 -- the structure of the foreign type.
228 (_, t_ty) = tcSplitForAllTys sig_ty
229 (arg_tys, res_ty) = tcSplitFunTys t_ty
234 %************************************************************************
236 \subsection{Miscellaneous}
238 %************************************************************************
241 ------------ Checking argument types for foreign import ----------------------
242 checkForeignArgs :: (Type -> Bool) -> [Type] -> NF_TcM ()
243 checkForeignArgs pred tys
244 = mapNF_Tc go tys `thenNF_Tc_` returnNF_Tc ()
246 go ty = check (pred ty) (illegalForeignTyErr argument ty)
249 ------------ Checking result types for foreign calls ----------------------
250 -- Check that the type has the form
251 -- (IO t) or (t) , and that t satisfies the given predicate.
253 checkForeignRes :: Bool -> (Type -> Bool) -> Type -> NF_TcM ()
258 checkForeignRes non_io_result_ok pred_res_ty ty
259 = case tcSplitTyConApp_maybe ty of
261 | io `hasKey` ioTyConKey && pred_res_ty res_ty
264 -> check (non_io_result_ok && pred_res_ty ty)
265 (illegalForeignTyErr result ty)
269 checkDotNet HscILX = Nothing
270 checkDotNet other = Just (text "requires .NET code generation (-filx)")
272 checkC HscC = Nothing
273 checkC other = Just (text "requires C code generation (-fvia-C)")
275 checkCOrAsm HscC = Nothing
276 checkCOrAsm HscAsm = Nothing
278 = Just (text "requires via-C or native code generation (-fvia-C)")
280 checkCOrAsmOrInterp HscC = Nothing
281 checkCOrAsmOrInterp HscAsm = Nothing
282 checkCOrAsmOrInterp HscInterpreted = Nothing
283 checkCOrAsmOrInterp other
284 = Just (text "requires interpreted, C or native code generation")
286 checkCOrAsmOrDotNet HscC = Nothing
287 checkCOrAsmOrDotNet HscAsm = Nothing
288 checkCOrAsmOrDotNet HscILX = Nothing
289 checkCOrAsmOrDotNet other
290 = Just (text "requires C, native or .NET ILX code generation")
292 checkCOrAsmOrDotNetOrInterp HscC = Nothing
293 checkCOrAsmOrDotNetOrInterp HscAsm = Nothing
294 checkCOrAsmOrDotNetOrInterp HscILX = Nothing
295 checkCOrAsmOrDotNetOrInterp HscInterpreted = Nothing
296 checkCOrAsmOrDotNetOrInterp other
297 = Just (text "requires interpreted, C, native or .NET ILX code generation")
300 = getDOptsTc `thenNF_Tc` \ dflags ->
301 let hscLang = dopt_HscLang dflags in
303 HscNothing -> returnNF_Tc ()
305 case check hscLang of
306 Nothing -> returnNF_Tc ()
307 Just err -> addErrTc (text "Illegal foreign declaration:" <+> err)
313 check :: Bool -> Message -> NF_TcM ()
314 check True _ = returnTc ()
315 check _ the_err = addErrTc the_err
317 illegalForeignTyErr arg_or_res ty
318 = hang (hsep [ptext SLIT("Unacceptable"), arg_or_res,
319 ptext SLIT("type in foreign declaration:")])
322 -- Used for 'arg_or_res' argument to illegalForeignTyErr
323 argument = text "argument"
324 result = text "result"
326 badCName :: CLabelString -> Message
328 = sep [quotes (ppr target) <+> ptext SLIT("is not a valid C identifier")]
331 = hang (ptext SLIT("When checking declaration:"))