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, 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 ( 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 :: [RenamedHsDecl] -> TcM ([Id], [TypecheckedForeignDecl])
76 tcForeignImports decls =
77 mapAndUnzipM 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)
83 addErrCtxt (foreignDeclCtxt fo) $
84 tcHsSigType (ForSigCtxt nm) hs_ty `thenM` \ 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 = mkVanillaGlobal nm sig_ty noCafIdInfo
91 -- Foreign-imported things don't neeed zonking etc
92 -- They are rather like constructors; we make the final
93 -- Global Id right away.
95 tcCheckFIType sig_ty arg_tys res_ty imp_decl `thenM_`
96 -- can't use sig_ty here because it :: Type and we need HsType Id
97 -- hence the undefined
98 returnM (id, ForeignImport id undefined imp_decl isDeprec src_loc)
102 ------------ Checking types for foreign import ----------------------
104 tcCheckFIType _ _ _ (DNImport _)
105 = checkCg checkDotNet
107 tcCheckFIType sig_ty arg_tys res_ty (CImport _ _ _ _ (CLabel _))
108 = checkCg checkCOrAsm `thenM_`
109 check (isFFILabelTy sig_ty) (illegalForeignTyErr empty sig_ty)
111 tcCheckFIType sig_ty arg_tys res_ty (CImport cconv _ _ _ CWrapper)
112 = -- Foreign wrapper (former f.e.d.)
113 -- The type must be of the form ft -> IO (FunPtr ft), where ft is a
114 -- valid foreign type. For legacy reasons ft -> IO (Ptr ft) as well
115 -- as ft -> IO Addr is accepted, too. The use of the latter two forms
116 -- is DEPRECATED, though.
117 checkCg (if cconv == StdCallConv
119 else checkCOrAsmOrInterp) `thenM_`
120 -- the native code gen can't handle foreign import stdcall "wrapper",
121 -- because it doesn't emit the '@n' suffix on the label of the
122 -- C stub function. Infrastructure changes are required to make this
123 -- happen; MachLabel will need to carry around information about
124 -- the arity of the foreign call.
126 [arg1_ty] -> checkForeignArgs isFFIExternalTy arg1_tys `thenM_`
127 checkForeignRes nonIOok isFFIExportResultTy res1_ty `thenM_`
128 checkForeignRes mustBeIO isFFIDynResultTy res_ty `thenM_`
129 checkFEDArgs arg1_tys
131 (arg1_tys, res1_ty) = tcSplitFunTys arg1_ty
132 other -> addErrTc (illegalForeignTyErr empty sig_ty)
134 tcCheckFIType sig_ty arg_tys res_ty (CImport _ safety _ _ (CFunction target))
135 | isDynamicTarget target -- Foreign import dynamic
136 = checkCg checkCOrAsmOrInterp `thenM_`
137 case arg_tys of -- The first arg must be Ptr, FunPtr, or Addr
138 [] -> check False (illegalForeignTyErr empty sig_ty)
139 (arg1_ty:arg_tys) -> getDOpts `thenM` \ dflags ->
140 check (isFFIDynArgumentTy arg1_ty)
141 (illegalForeignTyErr argument arg1_ty) `thenM_`
142 checkForeignArgs (isFFIArgumentTy dflags safety) arg_tys `thenM_`
143 checkForeignRes nonIOok (isFFIImportResultTy dflags) res_ty
145 | otherwise -- Normal foreign import
146 = checkCg (if isCasmTarget target
147 then checkC else checkCOrAsmOrDotNetOrInterp) `thenM_`
148 checkCTarget target `thenM_`
149 getDOpts `thenM` \ dflags ->
150 checkForeignArgs (isFFIArgumentTy dflags safety) arg_tys `thenM_`
151 checkForeignRes nonIOok (isFFIImportResultTy dflags) res_ty
153 -- This makes a convenient place to check
154 -- that the C identifier is valid for C
155 checkCTarget (StaticTarget str)
156 = checkCg checkCOrAsmOrDotNetOrInterp `thenM_`
157 check (isCLabelString str) (badCName str)
159 checkCTarget (CasmTarget _)
163 On an Alpha, with foreign export dynamic, due to a giant hack when
164 building adjustor thunks, we only allow 4 integer arguments with
165 foreign export dynamic (i.e., 32 bytes of arguments after padding each
166 argument to a quadword, excluding floating-point arguments).
168 The check is needed for both via-C and native-code routes
171 #include "nativeGen/NCG.h"
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 = returnM ()
186 %************************************************************************
190 %************************************************************************
193 tcForeignExports :: [RenamedHsDecl]
194 -> TcM (TcMonoBinds, [TcForeignDecl])
195 tcForeignExports decls =
196 foldlM combine (EmptyMonoBinds, [])
197 [foreign_decl | ForD foreign_decl <- decls, isForeignExport foreign_decl]
199 combine (binds, fs) fe =
200 tcFExport fe `thenM ` \ (b, f) ->
201 returnM (b `AndMonoBinds` binds, f:fs)
203 tcFExport :: RenamedForeignDecl -> TcM (TcMonoBinds, TcForeignDecl)
204 tcFExport fo@(ForeignExport nm hs_ty spec isDeprec src_loc) =
206 addErrCtxt (foreignDeclCtxt fo) $
208 tcHsSigType (ForSigCtxt nm) hs_ty `thenM` \ sig_ty ->
209 tcExpr (HsVar nm) sig_ty `thenM` \ rhs ->
211 tcCheckFEType sig_ty spec `thenM_`
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).
218 newUnique `thenM` \ uniq ->
219 getModule `thenM` \ mod ->
221 gnm = mkExternalName uniq mod (mkForeignExportOcc (getOccName nm)) src_loc
222 id = setIdLocalExported (mkLocalId gnm sig_ty)
223 bind = VarMonoBind id rhs
225 returnM (bind, ForeignExport id undefined spec isDeprec src_loc)
228 ------------ Checking argument types for foreign export ----------------------
231 tcCheckFEType sig_ty (CExport (CExportStatic str _))
232 = check (isCLabelString str) (badCName str) `thenM_`
233 checkForeignArgs isFFIExternalTy arg_tys `thenM_`
234 checkForeignRes nonIOok isFFIExportResultTy res_ty
236 -- Drop the foralls before inspecting n
237 -- the structure of the foreign type.
238 (_, t_ty) = tcSplitForAllTys sig_ty
239 (arg_tys, res_ty) = tcSplitFunTys t_ty
244 %************************************************************************
246 \subsection{Miscellaneous}
248 %************************************************************************
251 ------------ Checking argument types for foreign import ----------------------
252 checkForeignArgs :: (Type -> Bool) -> [Type] -> TcM ()
253 checkForeignArgs pred tys
254 = mappM go tys `thenM_`
257 go ty = check (pred ty) (illegalForeignTyErr argument ty)
259 ------------ Checking result types for foreign calls ----------------------
260 -- Check that the type has the form
261 -- (IO t) or (t) , and that t satisfies the given predicate.
263 checkForeignRes :: Bool -> (Type -> Bool) -> Type -> TcM ()
268 checkForeignRes non_io_result_ok pred_res_ty ty
269 = case tcSplitTyConApp_maybe ty of
271 | io `hasKey` ioTyConKey && pred_res_ty res_ty
274 -> check (non_io_result_ok && pred_res_ty ty)
275 (illegalForeignTyErr result ty)
279 checkDotNet HscILX = Nothing
280 checkDotNet other = Just (text "requires .NET code generation (-filx)")
282 checkC HscC = Nothing
283 checkC other = Just (text "requires C code generation (-fvia-C)")
285 checkCOrAsm HscC = Nothing
286 checkCOrAsm HscAsm = Nothing
288 = Just (text "requires via-C or native code generation (-fvia-C)")
290 checkCOrAsmOrInterp HscC = Nothing
291 checkCOrAsmOrInterp HscAsm = Nothing
292 checkCOrAsmOrInterp HscInterpreted = Nothing
293 checkCOrAsmOrInterp other
294 = Just (text "requires interpreted, C or native code generation")
296 checkCOrAsmOrDotNet HscC = Nothing
297 checkCOrAsmOrDotNet HscAsm = Nothing
298 checkCOrAsmOrDotNet HscILX = Nothing
299 checkCOrAsmOrDotNet other
300 = Just (text "requires C, native or .NET ILX code generation")
302 checkCOrAsmOrDotNetOrInterp HscC = Nothing
303 checkCOrAsmOrDotNetOrInterp HscAsm = Nothing
304 checkCOrAsmOrDotNetOrInterp HscILX = Nothing
305 checkCOrAsmOrDotNetOrInterp HscInterpreted = Nothing
306 checkCOrAsmOrDotNetOrInterp other
307 = Just (text "requires interpreted, C, native or .NET ILX code generation")
310 = getDOpts `thenM` \ dflags ->
311 let hscLang = dopt_HscLang dflags in
313 HscNothing -> returnM ()
315 case check hscLang of
316 Nothing -> returnM ()
317 Just err -> addErrTc (text "Illegal foreign declaration:" <+> err)
323 check :: Bool -> Message -> TcM ()
324 check True _ = returnM ()
325 check _ the_err = addErrTc the_err
327 illegalForeignTyErr arg_or_res ty
328 = hang (hsep [ptext SLIT("Unacceptable"), arg_or_res,
329 ptext SLIT("type in foreign declaration:")])
332 -- Used for 'arg_or_res' argument to illegalForeignTyErr
333 argument = text "argument"
334 result = text "result"
336 badCName :: CLabelString -> Message
338 = sep [quotes (ppr target) <+> ptext SLIT("is not a valid C identifier")]
341 = hang (ptext SLIT("When checking declaration:"))