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 ( newLocalId )
29 import TcMonoType ( tcHsSigType, UserTypeCtxt(..) )
30 import TcHsSyn ( TcMonoBinds, TypecheckedForeignDecl, TcForeignExportDecl )
31 import TcExpr ( tcPolyExpr )
32 import Inst ( emptyLIE, LIE, plusLIE )
34 import ErrUtils ( Message )
35 import Id ( Id, mkLocalId )
36 import Name ( nameOccName )
37 import TysWiredIn ( isFFIArgumentTy, isFFIImportResultTy,
39 isFFIExternalTy, isFFIDynArgumentTy, isFFIDynResultTy,
42 import PrimRep ( getPrimRepSize )
43 import Type ( typePrimRep )
44 import TcType ( Type, tcSplitFunTys, tcSplitTyConApp_maybe, tcSplitForAllTys )
45 import ForeignCall ( CCallSpec(..), CExportSpec(..), CCallTarget(..), isDynamicTarget, isCasmTarget )
46 import CStrings ( CLabelString, isCLabelString )
47 import PrelNames ( hasKey, ioTyConKey )
48 import CmdLineOpts ( dopt_HscLang, HscLang(..) )
55 isForeignImport :: ForeignDecl name -> Bool
56 isForeignImport (ForeignImport _ _ _ _) = True
57 isForeignImport _ = False
60 isForeignExport :: ForeignDecl name -> Bool
61 isForeignExport (ForeignExport _ _ _ _) = True
62 isForeignExport _ = False
65 %************************************************************************
69 %************************************************************************
72 tcForeignImports :: [RenamedHsDecl] -> TcM ([Id], [TypecheckedForeignDecl])
73 tcForeignImports decls =
74 mapAndUnzipTc tcFImport [ foreign_decl | ForD foreign_decl <- decls, isForeignImport foreign_decl]
76 tcFImport :: RenamedForeignDecl -> TcM (Id, TypecheckedForeignDecl)
77 tcFImport fo@(ForeignImport nm hs_ty imp_decl src_loc)
78 = tcAddSrcLoc src_loc $
79 tcAddErrCtxt (foreignDeclCtxt fo) $
80 tcHsSigType (ForSigCtxt nm) hs_ty `thenTc` \ sig_ty ->
82 -- drop the foralls before inspecting the structure
83 -- of the foreign type.
84 (_, t_ty) = tcSplitForAllTys sig_ty
85 (arg_tys, res_ty) = tcSplitFunTys t_ty
86 id = mkLocalId nm sig_ty
88 tcCheckFIType sig_ty arg_tys res_ty imp_decl `thenNF_Tc_`
89 returnTc (id, ForeignImport id undefined imp_decl src_loc)
93 ------------ Checking types for foreign import ----------------------
95 tcCheckFIType _ _ _ (DNImport _)
98 tcCheckFIType sig_ty arg_tys res_ty (LblImport _)
99 = checkCg checkCOrAsm `thenNF_Tc_`
100 check (isFFILabelTy sig_ty) (illegalForeignTyErr empty sig_ty)
102 tcCheckFIType sig_ty arg_tys res_ty (CDynImport _)
103 = -- Foreign export dynamic
104 -- The first (and only!) arg has got to be a function type
105 -- and it must return IO t; result type is IO Addr
106 checkCg checkCOrAsm `thenNF_Tc_`
108 [arg1_ty] -> checkForeignArgs isFFIExternalTy arg1_tys `thenNF_Tc_`
109 checkForeignRes nonIOok isFFIExportResultTy res1_ty `thenNF_Tc_`
110 checkForeignRes mustBeIO isFFIDynResultTy res_ty `thenNF_Tc_`
111 checkFEDArgs arg1_tys
113 (arg1_tys, res1_ty) = tcSplitFunTys arg1_ty
114 other -> addErrTc (illegalForeignTyErr empty sig_ty)
116 tcCheckFIType sig_ty arg_tys res_ty (CImport (CCallSpec target _ safety))
117 | isDynamicTarget target -- Foreign import dynamic
118 = checkCg checkCOrAsmOrInterp `thenNF_Tc_`
119 case arg_tys of -- The first arg must be Addr
120 [] -> check False (illegalForeignTyErr empty sig_ty)
121 (arg1_ty:arg_tys) -> getDOptsTc `thenNF_Tc` \ dflags ->
122 check (isFFIDynArgumentTy arg1_ty)
123 (illegalForeignTyErr argument arg1_ty) `thenNF_Tc_`
124 checkForeignArgs (isFFIArgumentTy dflags safety) arg_tys `thenNF_Tc_`
125 checkForeignRes nonIOok (isFFIImportResultTy dflags) res_ty
127 | otherwise -- Normal foreign import
128 = checkCg (if isCasmTarget target
129 then checkC else checkCOrAsmOrDotNetOrInterp) `thenNF_Tc_`
130 checkCTarget target `thenNF_Tc_`
131 getDOptsTc `thenNF_Tc` \ dflags ->
132 checkForeignArgs (isFFIArgumentTy dflags safety) arg_tys `thenNF_Tc_`
133 checkForeignRes nonIOok (isFFIImportResultTy dflags) res_ty
135 -- This makes a convenient place to check
136 -- that the C identifier is valid for C
137 checkCTarget (StaticTarget str)
138 = checkCg checkCOrAsmOrDotNetOrInterp `thenNF_Tc_`
139 check (isCLabelString str) (badCName str)
141 checkCTarget (CasmTarget _)
145 On a SPARC, with foreign export dynamic, due to a giant hack when building
146 adjustor thunks, we only allow 16 bytes of arguments!
148 So for example, args (Int,Double,Int) would be OK (1+2+1)
149 as would (Int,Int,Int,Int) (1+1+1+1) but not (Int,Double,Double) (1+2+2).
151 The check is needed for both via-C and native-code routes
154 #include "nativeGen/NCG.h"
155 #if sparc_TARGET_ARCH
157 = check (words_of_args <= 4) err
159 words_of_args = sum (map (getPrimRepSize . typePrimRep) arg_tys)
160 err = ptext SLIT("On SPARC, I can only handle 4 words of arguments to foreign export dynamic")
162 checkFEDArgs arg_tys = returnNF_Tc ()
167 %************************************************************************
171 %************************************************************************
174 tcForeignExports :: [RenamedHsDecl] -> TcM (LIE, TcMonoBinds, [TcForeignExportDecl])
175 tcForeignExports decls =
176 foldlTc combine (emptyLIE, EmptyMonoBinds, [])
177 [ foreign_decl | ForD foreign_decl <- decls, isForeignExport foreign_decl]
179 combine (lie, binds, fs) fe =
180 tcFExport fe `thenTc ` \ (a_lie, b, f) ->
181 returnTc (lie `plusLIE` a_lie, b `AndMonoBinds` binds, f:fs)
183 tcFExport :: RenamedForeignDecl -> TcM (LIE, TcMonoBinds, TcForeignExportDecl)
184 tcFExport fo@(ForeignExport nm hs_ty spec src_loc) =
185 tcAddSrcLoc src_loc $
186 tcAddErrCtxt (foreignDeclCtxt fo) $
188 tcHsSigType (ForSigCtxt nm) hs_ty `thenTc` \ sig_ty ->
189 tcPolyExpr (HsVar nm) sig_ty `thenTc` \ (rhs, lie, _, _, _) ->
191 tcCheckFEType sig_ty spec `thenTc_`
193 -- we're exporting a function, but at a type possibly more constrained
194 -- than its declared/inferred type. Hence the need
195 -- to create a local binding which will call the exported function
196 -- at a particular type (and, maybe, overloading).
197 newLocalId (nameOccName nm) sig_ty src_loc `thenNF_Tc` \ id ->
199 bind = VarMonoBind id rhs
201 returnTc (lie, bind, ForeignExport id undefined spec src_loc)
204 ------------ Checking argument types for foreign export ----------------------
207 tcCheckFEType sig_ty (CExport (CExportStatic str _))
208 = check (isCLabelString str) (badCName str) `thenNF_Tc_`
209 checkForeignArgs isFFIExternalTy arg_tys `thenNF_Tc_`
210 checkForeignRes nonIOok isFFIExportResultTy res_ty
212 -- Drop the foralls before inspecting n
213 -- the structure of the foreign type.
214 (_, t_ty) = tcSplitForAllTys sig_ty
215 (arg_tys, res_ty) = tcSplitFunTys t_ty
220 %************************************************************************
222 \subsection{Miscellaneous}
224 %************************************************************************
227 ------------ Checking argument types for foreign import ----------------------
228 checkForeignArgs :: (Type -> Bool) -> [Type] -> NF_TcM ()
229 checkForeignArgs pred tys
230 = mapNF_Tc go tys `thenNF_Tc_` returnNF_Tc ()
232 go ty = check (pred ty) (illegalForeignTyErr argument ty)
235 ------------ Checking result types for foreign calls ----------------------
236 -- Check that the type has the form
237 -- (IO t) or (t) , and that t satisfies the given predicate.
239 checkForeignRes :: Bool -> (Type -> Bool) -> Type -> NF_TcM ()
244 checkForeignRes non_io_result_ok pred_res_ty ty
245 = case tcSplitTyConApp_maybe ty of
247 | io `hasKey` ioTyConKey && pred_res_ty res_ty
250 -> check (non_io_result_ok && pred_res_ty ty)
251 (illegalForeignTyErr result ty)
255 checkDotNet HscILX = Nothing
256 checkDotNet other = Just (text "requires .NET code generation (-filx)")
258 checkC HscC = Nothing
259 checkC other = Just (text "requires C code generation (-fvia-C)")
261 checkCOrAsm HscC = Nothing
262 checkCOrAsm HscAsm = Nothing
264 = Just (text "requires via-C or native code generation (-fvia-C)")
266 checkCOrAsmOrInterp HscC = Nothing
267 checkCOrAsmOrInterp HscAsm = Nothing
268 checkCOrAsmOrInterp HscInterpreted = Nothing
269 checkCOrAsmOrInterp other
270 = Just (text "requires interpreted, C or native code generation")
272 checkCOrAsmOrDotNet HscC = Nothing
273 checkCOrAsmOrDotNet HscAsm = Nothing
274 checkCOrAsmOrDotNet HscILX = Nothing
275 checkCOrAsmOrDotNet other
276 = Just (text "requires C, native or .NET ILX code generation")
278 checkCOrAsmOrDotNetOrInterp HscC = Nothing
279 checkCOrAsmOrDotNetOrInterp HscAsm = Nothing
280 checkCOrAsmOrDotNetOrInterp HscILX = Nothing
281 checkCOrAsmOrDotNetOrInterp HscInterpreted = Nothing
282 checkCOrAsmOrDotNetOrInterp other
283 = Just (text "requires interpreted, C, native or .NET ILX code generation")
286 = getDOptsTc `thenNF_Tc` \ dflags ->
287 let hscLang = dopt_HscLang dflags in
289 HscNothing -> returnNF_Tc ()
291 case check hscLang of
292 Nothing -> returnNF_Tc ()
293 Just err -> addErrTc (text "Illegal foreign declaration:" <+> err)
299 check :: Bool -> Message -> NF_TcM ()
300 check True _ = returnTc ()
301 check _ the_err = addErrTc the_err
303 illegalForeignTyErr arg_or_res ty
304 = hang (hsep [ptext SLIT("Unacceptable"), arg_or_res,
305 ptext SLIT("type in foreign declaration:")])
308 -- Used for 'arg_or_res' argument to illegalForeignTyErr
309 argument = text "argument"
310 result = text "result"
312 badCName :: CLabelString -> Message
314 = sep [quotes (ppr target) <+> ptext SLIT("is not a valid C identifier")]
317 = hang (ptext SLIT("When checking declaration:"))