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,
48 import ForeignCall ( CExportSpec(..), CCallTarget(..), CCallConv(..),
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 cconv _ _ _ 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 (if cconv == StdCallConv
117 else checkCOrAsmOrInterp) `thenNF_Tc_`
118 -- the native code gen can't handle foreign import stdcall "wrapper",
119 -- because it doesn't emit the '@n' suffix on the label of the
120 -- C stub function. Infrastructure changes are required to make this
121 -- happen; MachLabel will need to carry around information about
122 -- the arity of the foreign call.
124 [arg1_ty] -> checkForeignArgs isFFIExternalTy arg1_tys `thenNF_Tc_`
125 checkForeignRes nonIOok isFFIExportResultTy res1_ty `thenNF_Tc_`
126 checkForeignRes mustBeIO isFFIDynResultTy res_ty `thenNF_Tc_`
127 checkFEDArgs arg1_tys
129 (arg1_tys, res1_ty) = tcSplitFunTys arg1_ty
130 other -> addErrTc (illegalForeignTyErr empty sig_ty)
132 tcCheckFIType sig_ty arg_tys res_ty (CImport _ safety _ _ (CFunction target))
133 | isDynamicTarget target -- Foreign import dynamic
134 = checkCg checkCOrAsmOrInterp `thenNF_Tc_`
135 case arg_tys of -- The first arg must be Ptr, FunPtr, or Addr
136 [] -> check False (illegalForeignTyErr empty sig_ty)
137 (arg1_ty:arg_tys) -> getDOptsTc `thenNF_Tc` \ dflags ->
138 check (isFFIDynArgumentTy arg1_ty)
139 (illegalForeignTyErr argument arg1_ty) `thenNF_Tc_`
140 checkForeignArgs (isFFIArgumentTy dflags safety) arg_tys `thenNF_Tc_`
141 checkForeignRes nonIOok (isFFIImportResultTy dflags) res_ty
143 | otherwise -- Normal foreign import
144 = checkCg (if isCasmTarget target
145 then checkC else checkCOrAsmOrDotNetOrInterp) `thenNF_Tc_`
146 checkCTarget target `thenNF_Tc_`
147 getDOptsTc `thenNF_Tc` \ dflags ->
148 checkForeignArgs (isFFIArgumentTy dflags safety) arg_tys `thenNF_Tc_`
149 checkForeignRes nonIOok (isFFIImportResultTy dflags) res_ty
151 -- This makes a convenient place to check
152 -- that the C identifier is valid for C
153 checkCTarget (StaticTarget str)
154 = checkCg checkCOrAsmOrDotNetOrInterp `thenNF_Tc_`
155 check (isCLabelString str) (badCName str)
157 checkCTarget (CasmTarget _)
161 On an Alpha, with foreign export dynamic, due to a giant hack when
162 building adjustor thunks, we only allow 4 integer arguments with
163 foreign export dynamic (i.e., 32 bytes of arguments after padding each
164 argument to a quadword, excluding floating-point arguments).
166 The check is needed for both via-C and native-code routes
169 #include "nativeGen/NCG.h"
170 #if alpha_TARGET_ARCH
172 = check (integral_args <= 4) err
174 integral_args = sum (map getPrimRepSize $
175 filter (not . isFloatingRep) $
176 map typePrimRep arg_tys)
177 err = ptext SLIT("On Alpha, I can only handle 4 non-floating-point arguments to foreign export dynamic")
179 checkFEDArgs arg_tys = returnNF_Tc ()
184 %************************************************************************
188 %************************************************************************
191 tcForeignExports :: Module -> [RenamedHsDecl]
192 -> TcM (LIE, TcMonoBinds, [TcForeignExportDecl])
193 tcForeignExports mod decls =
194 foldlTc combine (emptyLIE, EmptyMonoBinds, [])
195 [foreign_decl | ForD foreign_decl <- decls, isForeignExport foreign_decl]
197 combine (lie, binds, fs) fe =
198 tcFExport mod fe `thenTc ` \ (a_lie, b, f) ->
199 returnTc (lie `plusLIE` a_lie, b `AndMonoBinds` binds, f:fs)
201 tcFExport :: Module -> RenamedForeignDecl -> TcM (LIE, TcMonoBinds, TcForeignExportDecl)
202 tcFExport mod fo@(ForeignExport nm hs_ty spec isDeprec src_loc) =
203 tcAddSrcLoc src_loc $
204 tcAddErrCtxt (foreignDeclCtxt fo) $
206 tcHsSigType (ForSigCtxt nm) hs_ty `thenTc` \ sig_ty ->
207 tcExpr (HsVar nm) sig_ty `thenTc` \ (rhs, lie) ->
209 tcCheckFEType sig_ty spec `thenTc_`
211 -- we're exporting a function, but at a type possibly more
212 -- constrained than its declared/inferred type. Hence the need
213 -- to create a local binding which will call the exported function
214 -- at a particular type (and, maybe, overloading).
216 tcGetUnique `thenNF_Tc` \ uniq ->
218 gnm = mkExternalName uniq mod (mkForeignExportOcc (getOccName nm)) src_loc
219 id = setIdLocalExported (mkLocalId gnm 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)
256 ------------ Checking result types for foreign calls ----------------------
257 -- Check that the type has the form
258 -- (IO t) or (t) , and that t satisfies the given predicate.
260 checkForeignRes :: Bool -> (Type -> Bool) -> Type -> NF_TcM ()
265 checkForeignRes non_io_result_ok pred_res_ty ty
266 = case tcSplitTyConApp_maybe ty of
268 | io `hasKey` ioTyConKey && pred_res_ty res_ty
271 -> check (non_io_result_ok && pred_res_ty ty)
272 (illegalForeignTyErr result ty)
276 checkDotNet HscILX = Nothing
277 checkDotNet other = Just (text "requires .NET code generation (-filx)")
279 checkC HscC = Nothing
280 checkC other = Just (text "requires C code generation (-fvia-C)")
282 checkCOrAsm HscC = Nothing
283 checkCOrAsm HscAsm = Nothing
285 = Just (text "requires via-C or native code generation (-fvia-C)")
287 checkCOrAsmOrInterp HscC = Nothing
288 checkCOrAsmOrInterp HscAsm = Nothing
289 checkCOrAsmOrInterp HscInterpreted = Nothing
290 checkCOrAsmOrInterp other
291 = Just (text "requires interpreted, C or native code generation")
293 checkCOrAsmOrDotNet HscC = Nothing
294 checkCOrAsmOrDotNet HscAsm = Nothing
295 checkCOrAsmOrDotNet HscILX = Nothing
296 checkCOrAsmOrDotNet other
297 = Just (text "requires C, native or .NET ILX code generation")
299 checkCOrAsmOrDotNetOrInterp HscC = Nothing
300 checkCOrAsmOrDotNetOrInterp HscAsm = Nothing
301 checkCOrAsmOrDotNetOrInterp HscILX = Nothing
302 checkCOrAsmOrDotNetOrInterp HscInterpreted = Nothing
303 checkCOrAsmOrDotNetOrInterp other
304 = Just (text "requires interpreted, C, native or .NET ILX code generation")
307 = getDOptsTc `thenNF_Tc` \ dflags ->
308 let hscLang = dopt_HscLang dflags in
310 HscNothing -> returnNF_Tc ()
312 case check hscLang of
313 Nothing -> returnNF_Tc ()
314 Just err -> addErrTc (text "Illegal foreign declaration:" <+> err)
320 check :: Bool -> Message -> NF_TcM ()
321 check True _ = returnTc ()
322 check _ the_err = addErrTc the_err
324 illegalForeignTyErr arg_or_res ty
325 = hang (hsep [ptext SLIT("Unacceptable"), arg_or_res,
326 ptext SLIT("type in foreign declaration:")])
329 -- Used for 'arg_or_res' argument to illegalForeignTyErr
330 argument = text "argument"
331 result = text "result"
333 badCName :: CLabelString -> Message
335 = sep [quotes (ppr target) <+> ptext SLIT("is not a valid C identifier")]
338 = hang (ptext SLIT("When checking declaration:"))