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 ( ForeignDecl(..), HsExpr(..),
23 MonoBinds(..), ForeignImport(..), ForeignExport(..),
26 import RnHsSyn ( RenamedForeignDecl )
29 import TcMonoType ( tcHsSigType, UserTypeCtxt(..) )
30 import TcHsSyn ( TcMonoBinds, TypecheckedForeignDecl, TcForeignDecl )
31 import TcExpr ( tcExpr )
33 import ErrUtils ( Message )
34 import Id ( Id, mkLocalId, mkVanillaGlobal, setIdLocalExported )
35 import IdInfo ( noCafIdInfo )
36 import PrimRep ( getPrimRepSize, isFloatingRep )
37 import Type ( typePrimRep )
38 import OccName ( mkForeignExportOcc )
39 import Name ( Name, NamedThing(..), mkExternalName )
40 import TcType ( Type, tcSplitFunTys, tcSplitTyConApp_maybe,
42 isFFIArgumentTy, isFFIImportResultTy,
43 isFFIExportResultTy, isFFILabelTy,
44 isFFIExternalTy, isFFIDynArgumentTy,
47 import ForeignCall ( CExportSpec(..), CCallTarget(..), CCallConv(..),
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 :: [ForeignDecl Name] -> TcM ([Id], [TypecheckedForeignDecl])
76 tcForeignImports decls
77 = mapAndUnzipM tcFImport (filter isForeignImport decls)
79 tcFImport :: RenamedForeignDecl -> TcM (Id, TypecheckedForeignDecl)
80 tcFImport fo@(ForeignImport nm hs_ty imp_decl isDeprec src_loc)
82 addErrCtxt (foreignDeclCtxt fo) $
83 tcHsSigType (ForSigCtxt nm) hs_ty `thenM` \ sig_ty ->
85 -- drop the foralls before inspecting the structure
86 -- of the foreign type.
87 (_, t_ty) = tcSplitForAllTys sig_ty
88 (arg_tys, res_ty) = tcSplitFunTys t_ty
89 id = mkVanillaGlobal nm sig_ty noCafIdInfo
90 -- Foreign-imported things don't neeed zonking etc
91 -- They are rather like constructors; we make the final
92 -- Global Id right away.
94 tcCheckFIType sig_ty arg_tys res_ty imp_decl `thenM_`
95 -- can't use sig_ty here because it :: Type and we need HsType Id
96 -- hence the undefined
97 returnM (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 `thenM_`
108 check (isFFILabelTy sig_ty) (illegalForeignTyErr empty sig_ty)
110 tcCheckFIType sig_ty arg_tys res_ty (CImport cconv _ _ _ 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 `thenM_`
118 [arg1_ty] -> checkForeignArgs isFFIExternalTy arg1_tys `thenM_`
119 checkForeignRes nonIOok isFFIExportResultTy res1_ty `thenM_`
120 checkForeignRes mustBeIO isFFIDynResultTy res_ty `thenM_`
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 `thenM_`
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) -> getDOpts `thenM` \ dflags ->
132 check (isFFIDynArgumentTy arg1_ty)
133 (illegalForeignTyErr argument arg1_ty) `thenM_`
134 checkForeignArgs (isFFIArgumentTy dflags safety) arg_tys `thenM_`
135 checkForeignRes nonIOok (isFFIImportResultTy dflags) res_ty
137 | otherwise -- Normal foreign import
138 = checkCg (if isCasmTarget target
139 then checkC else checkCOrAsmOrDotNetOrInterp) `thenM_`
140 checkCTarget target `thenM_`
141 getDOpts `thenM` \ dflags ->
142 checkForeignArgs (isFFIArgumentTy dflags safety) arg_tys `thenM_`
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 `thenM_`
149 check (isCLabelString str) (badCName str)
151 checkCTarget (CasmTarget _)
155 On an Alpha, with foreign export dynamic, due to a giant hack when
156 building adjustor thunks, we only allow 4 integer arguments with
157 foreign export dynamic (i.e., 32 bytes of arguments after padding each
158 argument to a quadword, excluding floating-point arguments).
160 The check is needed for both via-C and native-code routes
163 #include "nativeGen/NCG.h"
164 #if alpha_TARGET_ARCH
166 = check (integral_args <= 4) err
168 integral_args = sum (map getPrimRepSize $
169 filter (not . isFloatingRep) $
170 map typePrimRep arg_tys)
171 err = ptext SLIT("On Alpha, I can only handle 4 non-floating-point arguments to foreign export dynamic")
173 checkFEDArgs arg_tys = returnM ()
178 %************************************************************************
182 %************************************************************************
185 tcForeignExports :: [ForeignDecl Name]
186 -> TcM (TcMonoBinds, [TcForeignDecl])
187 tcForeignExports decls
188 = foldlM combine (EmptyMonoBinds, []) (filter isForeignExport decls)
190 combine (binds, fs) fe =
191 tcFExport fe `thenM ` \ (b, f) ->
192 returnM (b `AndMonoBinds` binds, f:fs)
194 tcFExport :: RenamedForeignDecl -> TcM (TcMonoBinds, TcForeignDecl)
195 tcFExport fo@(ForeignExport nm hs_ty spec isDeprec src_loc) =
197 addErrCtxt (foreignDeclCtxt fo) $
199 tcHsSigType (ForSigCtxt nm) hs_ty `thenM` \ sig_ty ->
200 tcExpr (HsVar nm) sig_ty `thenM` \ rhs ->
202 tcCheckFEType sig_ty spec `thenM_`
204 -- we're exporting a function, but at a type possibly more
205 -- constrained than its declared/inferred type. Hence the need
206 -- to create a local binding which will call the exported function
207 -- at a particular type (and, maybe, overloading).
209 newUnique `thenM` \ uniq ->
210 getModule `thenM` \ mod ->
212 gnm = mkExternalName uniq mod (mkForeignExportOcc (getOccName nm)) src_loc
213 id = setIdLocalExported (mkLocalId gnm sig_ty)
214 bind = VarMonoBind id rhs
216 returnM (bind, ForeignExport id undefined spec isDeprec src_loc)
219 ------------ Checking argument types for foreign export ----------------------
222 tcCheckFEType sig_ty (CExport (CExportStatic str _))
223 = check (isCLabelString str) (badCName str) `thenM_`
224 checkForeignArgs isFFIExternalTy arg_tys `thenM_`
225 checkForeignRes nonIOok isFFIExportResultTy res_ty
227 -- Drop the foralls before inspecting n
228 -- the structure of the foreign type.
229 (_, t_ty) = tcSplitForAllTys sig_ty
230 (arg_tys, res_ty) = tcSplitFunTys t_ty
235 %************************************************************************
237 \subsection{Miscellaneous}
239 %************************************************************************
242 ------------ Checking argument types for foreign import ----------------------
243 checkForeignArgs :: (Type -> Bool) -> [Type] -> TcM ()
244 checkForeignArgs pred tys
245 = mappM go tys `thenM_`
248 go ty = check (pred ty) (illegalForeignTyErr argument ty)
250 ------------ Checking result types for foreign calls ----------------------
251 -- Check that the type has the form
252 -- (IO t) or (t) , and that t satisfies the given predicate.
254 checkForeignRes :: Bool -> (Type -> Bool) -> Type -> TcM ()
259 checkForeignRes non_io_result_ok pred_res_ty ty
260 = case tcSplitTyConApp_maybe ty of
262 | io `hasKey` ioTyConKey && pred_res_ty res_ty
265 -> check (non_io_result_ok && pred_res_ty ty)
266 (illegalForeignTyErr result ty)
270 checkDotNet HscILX = Nothing
271 checkDotNet other = Just (text "requires .NET code generation (-filx)")
273 checkC HscC = Nothing
274 checkC other = Just (text "requires C code generation (-fvia-C)")
276 checkCOrAsm HscC = Nothing
277 checkCOrAsm HscAsm = Nothing
279 = Just (text "requires via-C or native code generation (-fvia-C)")
281 checkCOrAsmOrInterp HscC = Nothing
282 checkCOrAsmOrInterp HscAsm = Nothing
283 checkCOrAsmOrInterp HscInterpreted = Nothing
284 checkCOrAsmOrInterp other
285 = Just (text "requires interpreted, C or native code generation")
287 checkCOrAsmOrDotNet HscC = Nothing
288 checkCOrAsmOrDotNet HscAsm = Nothing
289 checkCOrAsmOrDotNet HscILX = Nothing
290 checkCOrAsmOrDotNet other
291 = Just (text "requires C, native or .NET ILX code generation")
293 checkCOrAsmOrDotNetOrInterp HscC = Nothing
294 checkCOrAsmOrDotNetOrInterp HscAsm = Nothing
295 checkCOrAsmOrDotNetOrInterp HscILX = Nothing
296 checkCOrAsmOrDotNetOrInterp HscInterpreted = Nothing
297 checkCOrAsmOrDotNetOrInterp other
298 = Just (text "requires interpreted, C, native or .NET ILX code generation")
301 = getDOpts `thenM` \ dflags ->
302 let hscLang = dopt_HscLang dflags in
304 HscNothing -> returnM ()
306 case check hscLang of
307 Nothing -> returnM ()
308 Just err -> addErrTc (text "Illegal foreign declaration:" <+> err)
314 check :: Bool -> Message -> TcM ()
315 check True _ = returnM ()
316 check _ the_err = addErrTc the_err
318 illegalForeignTyErr arg_or_res ty
319 = hang (hsep [ptext SLIT("Unacceptable"), arg_or_res,
320 ptext SLIT("type in foreign declaration:")])
323 -- Used for 'arg_or_res' argument to illegalForeignTyErr
324 argument = text "argument"
325 result = text "result"
327 badCName :: CLabelString -> Message
329 = sep [quotes (ppr target) <+> ptext SLIT("is not a valid C identifier")]
332 = hang (ptext SLIT("When checking declaration:"))