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 "../includes/ghcconfig.h"
21 #include "HsVersions.h"
26 import TcHsType ( tcHsSigType, UserTypeCtxt(..) )
27 import TcExpr ( tcCheckSigma )
29 import ErrUtils ( Message )
30 import Id ( Id, mkLocalId, mkExportedLocalId )
32 import PrimRep ( getPrimRepSize, isFloatingRep )
33 import Type ( typePrimRep )
35 import OccName ( mkForeignExportOcc )
36 import Name ( Name, NamedThing(..), mkExternalName )
37 import TcType ( Type, tcSplitFunTys, tcSplitTyConApp_maybe,
39 isFFIArgumentTy, isFFIImportResultTy,
40 isFFIExportResultTy, isFFILabelTy,
41 isFFIExternalTy, isFFIDynArgumentTy,
42 isFFIDynResultTy, isFFIDotnetTy, isFFIDotnetObjTy,
45 import ForeignCall ( CExportSpec(..), CCallTarget(..),
46 CLabelString, isCLabelString,
47 isDynamicTarget, withDNTypes, DNKind(..), DNCallSpec(..) )
48 import MachOp ( machRepByteWidth )
49 import PrelNames ( hasKey, ioTyConKey )
50 import CmdLineOpts ( dopt_HscLang, HscLang(..) )
52 import SrcLoc ( Located(..), srcSpanStart )
53 import Bag ( emptyBag, consBag )
59 isForeignImport :: LForeignDecl name -> Bool
60 isForeignImport (L _ (ForeignImport _ _ _ _)) = True
61 isForeignImport _ = False
64 isForeignExport :: LForeignDecl name -> Bool
65 isForeignExport (L _ (ForeignExport _ _ _ _)) = True
66 isForeignExport _ = False
69 %************************************************************************
73 %************************************************************************
76 tcForeignImports :: [LForeignDecl Name] -> TcM ([Id], [LForeignDecl Id])
77 tcForeignImports decls
78 = mapAndUnzipM (wrapLocSndM tcFImport) (filter isForeignImport decls)
80 tcFImport :: ForeignDecl Name -> TcM (Id, ForeignDecl Id)
81 tcFImport fo@(ForeignImport (L loc nm) hs_ty imp_decl isDeprec)
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 = mkLocalId nm sig_ty
90 -- Use a LocalId to obey the invariant that locally-defined
91 -- things are LocalIds. However, it does not need zonking,
92 -- (so TcHsSyn.zonkForeignExports ignores it).
94 tcCheckFIType sig_ty arg_tys res_ty imp_decl `thenM` \ imp_decl' ->
95 -- can't use sig_ty here because it :: Type and we need HsType Id
96 -- hence the undefined
97 returnM (id, ForeignImport (L loc id) undefined imp_decl' isDeprec)
101 ------------ Checking types for foreign import ----------------------
103 tcCheckFIType _ arg_tys res_ty (DNImport spec)
104 = checkCg checkDotnet `thenM_`
105 getDOpts `thenM` \ dflags ->
106 checkForeignArgs (isFFIDotnetTy dflags) arg_tys `thenM_`
107 checkForeignRes True{-non IO ok-} (isFFIDotnetTy dflags) res_ty `thenM_`
108 let (DNCallSpec isStatic kind _ _ _ _) = spec in
110 DNMethod | not isStatic ->
112 [] -> addErrTc illegalDNMethodSig
114 | not (isFFIDotnetObjTy (last arg_tys)) -> addErrTc illegalDNMethodSig
115 | otherwise -> returnM ()
116 _ -> returnM ()) `thenM_`
117 returnM (DNImport (withDNTypes spec (map toDNType arg_tys) (toDNType res_ty)))
119 tcCheckFIType sig_ty arg_tys res_ty idecl@(CImport _ _ _ _ (CLabel _))
120 = checkCg checkCOrAsm `thenM_`
121 check (isFFILabelTy sig_ty) (illegalForeignTyErr empty sig_ty) `thenM_`
124 tcCheckFIType sig_ty arg_tys res_ty idecl@(CImport cconv _ _ _ CWrapper)
125 = -- Foreign wrapper (former f.e.d.)
126 -- The type must be of the form ft -> IO (FunPtr ft), where ft is a
127 -- valid foreign type. For legacy reasons ft -> IO (Ptr ft) as well
128 -- as ft -> IO Addr is accepted, too. The use of the latter two forms
129 -- is DEPRECATED, though.
130 checkCg checkCOrAsmOrInterp `thenM_`
132 [arg1_ty] -> checkForeignArgs isFFIExternalTy arg1_tys `thenM_`
133 checkForeignRes nonIOok isFFIExportResultTy res1_ty `thenM_`
134 checkForeignRes mustBeIO isFFIDynResultTy res_ty `thenM_`
135 checkFEDArgs arg1_tys
137 (arg1_tys, res1_ty) = tcSplitFunTys arg1_ty
138 other -> addErrTc (illegalForeignTyErr empty sig_ty) ) `thenM_`
141 tcCheckFIType sig_ty arg_tys res_ty idecl@(CImport _ safety _ _ (CFunction target))
142 | isDynamicTarget target -- Foreign import dynamic
143 = checkCg checkCOrAsmOrInterp `thenM_`
144 case arg_tys of -- The first arg must be Ptr, FunPtr, or Addr
146 check False (illegalForeignTyErr empty sig_ty) `thenM_`
149 getDOpts `thenM` \ dflags ->
150 check (isFFIDynArgumentTy arg1_ty)
151 (illegalForeignTyErr argument arg1_ty) `thenM_`
152 checkForeignArgs (isFFIArgumentTy dflags safety) arg_tys `thenM_`
153 checkForeignRes nonIOok (isFFIImportResultTy dflags) res_ty `thenM_`
155 | otherwise -- Normal foreign import
156 = checkCg (checkCOrAsmOrDotNetOrInterp) `thenM_`
157 checkCTarget target `thenM_`
158 getDOpts `thenM` \ dflags ->
159 checkForeignArgs (isFFIArgumentTy dflags safety) arg_tys `thenM_`
160 checkForeignRes nonIOok (isFFIImportResultTy dflags) res_ty `thenM_`
163 -- This makes a convenient place to check
164 -- that the C identifier is valid for C
165 checkCTarget (StaticTarget str)
166 = checkCg checkCOrAsmOrDotNetOrInterp `thenM_`
167 check (isCLabelString str) (badCName str)
170 On an Alpha, with foreign export dynamic, due to a giant hack when
171 building adjustor thunks, we only allow 4 integer arguments with
172 foreign export dynamic (i.e., 32 bytes of arguments after padding each
173 argument to a quadword, excluding floating-point arguments).
175 The check is needed for both via-C and native-code routes
178 #include "nativeGen/NCG.h"
179 #if alpha_TARGET_ARCH
181 = check (integral_args <= 32) err
183 integral_args = sum [ machRepByteWidth rep
184 | (rep,hint) <- map typeMachRepRep arg_tys,
186 err = ptext SLIT("On Alpha, I can only handle 4 non-floating-point arguments to foreign export dynamic")
188 checkFEDArgs arg_tys = returnM ()
193 %************************************************************************
197 %************************************************************************
200 tcForeignExports :: [LForeignDecl Name]
201 -> TcM (LHsBinds TcId, [LForeignDecl TcId])
202 tcForeignExports decls
203 = foldlM combine (emptyBag, []) (filter isForeignExport decls)
205 combine (binds, fs) fe =
206 wrapLocSndM tcFExport fe `thenM` \ (b, f) ->
207 returnM (b `consBag` binds, f:fs)
209 tcFExport :: ForeignDecl Name -> TcM (LHsBind Id, ForeignDecl Id)
210 tcFExport fo@(ForeignExport (L loc nm) hs_ty spec isDeprec) =
211 addErrCtxt (foreignDeclCtxt fo) $
213 tcHsSigType (ForSigCtxt nm) hs_ty `thenM` \ sig_ty ->
214 tcCheckSigma (nlHsVar nm) sig_ty `thenM` \ rhs ->
216 tcCheckFEType sig_ty spec `thenM_`
218 -- we're exporting a function, but at a type possibly more
219 -- constrained than its declared/inferred type. Hence the need
220 -- to create a local binding which will call the exported function
221 -- at a particular type (and, maybe, overloading).
223 newUnique `thenM` \ uniq ->
224 getModule `thenM` \ mod ->
226 gnm = mkExternalName uniq mod (mkForeignExportOcc (getOccName nm))
227 Nothing (srcSpanStart loc)
228 id = mkExportedLocalId gnm sig_ty
229 bind = L loc (VarBind id rhs)
231 returnM (bind, ForeignExport (L loc id) undefined spec isDeprec)
234 ------------ Checking argument types for foreign export ----------------------
237 tcCheckFEType sig_ty (CExport (CExportStatic str _))
238 = check (isCLabelString str) (badCName str) `thenM_`
239 checkForeignArgs isFFIExternalTy arg_tys `thenM_`
240 checkForeignRes nonIOok isFFIExportResultTy res_ty
242 -- Drop the foralls before inspecting n
243 -- the structure of the foreign type.
244 (_, t_ty) = tcSplitForAllTys sig_ty
245 (arg_tys, res_ty) = tcSplitFunTys t_ty
250 %************************************************************************
252 \subsection{Miscellaneous}
254 %************************************************************************
257 ------------ Checking argument types for foreign import ----------------------
258 checkForeignArgs :: (Type -> Bool) -> [Type] -> TcM ()
259 checkForeignArgs pred tys
260 = mappM go tys `thenM_`
263 go ty = check (pred ty) (illegalForeignTyErr argument ty)
265 ------------ Checking result types for foreign calls ----------------------
266 -- Check that the type has the form
267 -- (IO t) or (t) , and that t satisfies the given predicate.
269 checkForeignRes :: Bool -> (Type -> Bool) -> Type -> TcM ()
274 checkForeignRes non_io_result_ok pred_res_ty ty
275 = case tcSplitTyConApp_maybe ty of
277 | io `hasKey` ioTyConKey && pred_res_ty res_ty
280 -> check (non_io_result_ok && pred_res_ty ty)
281 (illegalForeignTyErr result ty)
285 checkDotnet HscILX = Nothing
286 #if defined(mingw32_TARGET_OS)
287 checkDotnet HscC = Nothing
288 checkDotnet _ = Just (text "requires C code generation (-fvia-C)")
290 checkDotnet other = Just (text "requires .NET support (-filx or win32)")
293 checkCOrAsm HscC = Nothing
294 checkCOrAsm HscAsm = Nothing
296 = Just (text "requires via-C or native code generation (-fvia-C)")
298 checkCOrAsmOrInterp HscC = Nothing
299 checkCOrAsmOrInterp HscAsm = Nothing
300 checkCOrAsmOrInterp HscInterpreted = Nothing
301 checkCOrAsmOrInterp other
302 = Just (text "requires interpreted, C or native code generation")
304 checkCOrAsmOrDotNetOrInterp HscC = Nothing
305 checkCOrAsmOrDotNetOrInterp HscAsm = Nothing
306 checkCOrAsmOrDotNetOrInterp HscILX = Nothing
307 checkCOrAsmOrDotNetOrInterp HscInterpreted = Nothing
308 checkCOrAsmOrDotNetOrInterp other
309 = Just (text "requires interpreted, C, native or .NET ILX code generation")
312 = getDOpts `thenM` \ dflags ->
313 let hscLang = dopt_HscLang dflags in
315 HscNothing -> returnM ()
317 case check hscLang of
318 Nothing -> returnM ()
319 Just err -> addErrTc (text "Illegal foreign declaration:" <+> err)
325 check :: Bool -> Message -> TcM ()
326 check True _ = returnM ()
327 check _ the_err = addErrTc the_err
329 illegalForeignTyErr arg_or_res ty
330 = hang (hsep [ptext SLIT("Unacceptable"), arg_or_res,
331 ptext SLIT("type in foreign declaration:")])
334 -- Used for 'arg_or_res' argument to illegalForeignTyErr
335 argument = text "argument"
336 result = text "result"
338 badCName :: CLabelString -> Message
340 = sep [quotes (ppr target) <+> ptext SLIT("is not a valid C identifier")]
343 = hang (ptext SLIT("When checking declaration:"))
347 = ptext SLIT("'This pointer' expected as last argument")