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.
21 #include "HsVersions.h"
26 import TcHsType ( tcHsSigType, UserTypeCtxt(..) )
27 import TcExpr ( tcCheckSigma )
29 import ErrUtils ( Message )
30 import Id ( Id, mkLocalId, mkExportedLocalId )
31 import OccName ( mkForeignExportOcc )
32 import Name ( Name, NamedThing(..), mkExternalName )
33 import TcType ( Type, tcSplitFunTys, tcSplitTyConApp_maybe,
35 isFFIArgumentTy, isFFIImportResultTy,
36 isFFIExportResultTy, isFFILabelTy,
37 isFFIExternalTy, isFFIDynArgumentTy,
38 isFFIDynResultTy, isFFIDotnetTy, isFFIDotnetObjTy,
41 import ForeignCall ( CExportSpec(..), CCallTarget(..),
42 isDynamicTarget, withDNTypes, DNKind(..), DNCallSpec(..) )
43 import CStrings ( CLabelString, isCLabelString )
44 import PrelNames ( hasKey, ioTyConKey )
45 import CmdLineOpts ( dopt_HscLang, HscLang(..) )
47 import SrcLoc ( Located(..), srcSpanStart )
48 import Bag ( emptyBag, consBag )
54 isForeignImport :: LForeignDecl name -> Bool
55 isForeignImport (L _ (ForeignImport _ _ _ _)) = True
56 isForeignImport _ = False
59 isForeignExport :: LForeignDecl name -> Bool
60 isForeignExport (L _ (ForeignExport _ _ _ _)) = True
61 isForeignExport _ = False
64 %************************************************************************
68 %************************************************************************
71 tcForeignImports :: [LForeignDecl Name] -> TcM ([Id], [LForeignDecl Id])
72 tcForeignImports decls
73 = mapAndUnzipM (wrapLocSndM tcFImport) (filter isForeignImport decls)
75 tcFImport :: ForeignDecl Name -> TcM (Id, ForeignDecl Id)
76 tcFImport fo@(ForeignImport (L loc nm) hs_ty imp_decl isDeprec)
77 = addErrCtxt (foreignDeclCtxt fo) $
78 tcHsSigType (ForSigCtxt nm) hs_ty `thenM` \ sig_ty ->
80 -- drop the foralls before inspecting the structure
81 -- of the foreign type.
82 (_, t_ty) = tcSplitForAllTys sig_ty
83 (arg_tys, res_ty) = tcSplitFunTys t_ty
84 id = mkLocalId nm sig_ty
85 -- Use a LocalId to obey the invariant that locally-defined
86 -- things are LocalIds. However, it does not need zonking,
87 -- (so TcHsSyn.zonkForeignExports ignores it).
89 tcCheckFIType sig_ty arg_tys res_ty imp_decl `thenM` \ imp_decl' ->
90 -- can't use sig_ty here because it :: Type and we need HsType Id
91 -- hence the undefined
92 returnM (id, ForeignImport (L loc id) undefined imp_decl' isDeprec)
96 ------------ Checking types for foreign import ----------------------
98 tcCheckFIType _ arg_tys res_ty (DNImport spec)
99 = checkCg checkDotnet `thenM_`
100 getDOpts `thenM` \ dflags ->
101 checkForeignArgs (isFFIDotnetTy dflags) arg_tys `thenM_`
102 checkForeignRes True{-non IO ok-} (isFFIDotnetTy dflags) res_ty `thenM_`
103 let (DNCallSpec isStatic kind _ _ _ _) = spec in
105 DNMethod | not isStatic ->
107 [] -> addErrTc illegalDNMethodSig
109 | not (isFFIDotnetObjTy (last arg_tys)) -> addErrTc illegalDNMethodSig
110 | otherwise -> returnM ()
111 _ -> returnM ()) `thenM_`
112 returnM (DNImport (withDNTypes spec (map toDNType arg_tys) (toDNType res_ty)))
114 tcCheckFIType sig_ty arg_tys res_ty idecl@(CImport _ _ _ _ (CLabel _))
115 = checkCg checkCOrAsm `thenM_`
116 check (isFFILabelTy sig_ty) (illegalForeignTyErr empty sig_ty) `thenM_`
119 tcCheckFIType sig_ty arg_tys res_ty idecl@(CImport cconv _ _ _ CWrapper)
120 = -- Foreign wrapper (former f.e.d.)
121 -- The type must be of the form ft -> IO (FunPtr ft), where ft is a
122 -- valid foreign type. For legacy reasons ft -> IO (Ptr ft) as well
123 -- as ft -> IO Addr is accepted, too. The use of the latter two forms
124 -- is DEPRECATED, though.
125 checkCg checkCOrAsmOrInterp `thenM_`
127 [arg1_ty] -> checkForeignArgs isFFIExternalTy arg1_tys `thenM_`
128 checkForeignRes nonIOok isFFIExportResultTy res1_ty `thenM_`
129 checkForeignRes mustBeIO isFFIDynResultTy res_ty `thenM_`
130 checkFEDArgs arg1_tys
132 (arg1_tys, res1_ty) = tcSplitFunTys arg1_ty
133 other -> addErrTc (illegalForeignTyErr empty sig_ty) ) `thenM_`
136 tcCheckFIType sig_ty arg_tys res_ty idecl@(CImport _ safety _ _ (CFunction target))
137 | isDynamicTarget target -- Foreign import dynamic
138 = checkCg checkCOrAsmOrInterp `thenM_`
139 case arg_tys of -- The first arg must be Ptr, FunPtr, or Addr
141 check False (illegalForeignTyErr empty sig_ty) `thenM_`
144 getDOpts `thenM` \ dflags ->
145 check (isFFIDynArgumentTy arg1_ty)
146 (illegalForeignTyErr argument arg1_ty) `thenM_`
147 checkForeignArgs (isFFIArgumentTy dflags safety) arg_tys `thenM_`
148 checkForeignRes nonIOok (isFFIImportResultTy dflags) res_ty `thenM_`
150 | otherwise -- Normal foreign import
151 = checkCg (checkCOrAsmOrDotNetOrInterp) `thenM_`
152 checkCTarget target `thenM_`
153 getDOpts `thenM` \ dflags ->
154 checkForeignArgs (isFFIArgumentTy dflags safety) arg_tys `thenM_`
155 checkForeignRes nonIOok (isFFIImportResultTy dflags) res_ty `thenM_`
158 -- This makes a convenient place to check
159 -- that the C identifier is valid for C
160 checkCTarget (StaticTarget str)
161 = checkCg checkCOrAsmOrDotNetOrInterp `thenM_`
162 check (isCLabelString str) (badCName str)
165 On an Alpha, with foreign export dynamic, due to a giant hack when
166 building adjustor thunks, we only allow 4 integer arguments with
167 foreign export dynamic (i.e., 32 bytes of arguments after padding each
168 argument to a quadword, excluding floating-point arguments).
170 The check is needed for both via-C and native-code routes
173 #include "nativeGen/NCG.h"
174 #if alpha_TARGET_ARCH
176 = check (integral_args <= 4) err
178 integral_args = sum (map getPrimRepSize $
179 filter (not . isFloatingRep) $
180 map typePrimRep arg_tys)
181 err = ptext SLIT("On Alpha, I can only handle 4 non-floating-point arguments to foreign export dynamic")
183 checkFEDArgs arg_tys = returnM ()
188 %************************************************************************
192 %************************************************************************
195 tcForeignExports :: [LForeignDecl Name]
196 -> TcM (LHsBinds TcId, [LForeignDecl TcId])
197 tcForeignExports decls
198 = foldlM combine (emptyBag, []) (filter isForeignExport decls)
200 combine (binds, fs) fe =
201 wrapLocSndM tcFExport fe `thenM` \ (b, f) ->
202 returnM (b `consBag` binds, f:fs)
204 tcFExport :: ForeignDecl Name -> TcM (LHsBind Id, ForeignDecl Id)
205 tcFExport fo@(ForeignExport (L loc nm) hs_ty spec isDeprec) =
206 addErrCtxt (foreignDeclCtxt fo) $
208 tcHsSigType (ForSigCtxt nm) hs_ty `thenM` \ sig_ty ->
209 tcCheckSigma (nlHsVar 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))
222 Nothing (srcSpanStart loc)
223 id = mkExportedLocalId gnm sig_ty
224 bind = L loc (VarBind id rhs)
226 returnM (bind, ForeignExport (L loc id) undefined spec isDeprec)
229 ------------ Checking argument types for foreign export ----------------------
232 tcCheckFEType sig_ty (CExport (CExportStatic str _))
233 = check (isCLabelString str) (badCName str) `thenM_`
234 checkForeignArgs isFFIExternalTy arg_tys `thenM_`
235 checkForeignRes nonIOok isFFIExportResultTy res_ty
237 -- Drop the foralls before inspecting n
238 -- the structure of the foreign type.
239 (_, t_ty) = tcSplitForAllTys sig_ty
240 (arg_tys, res_ty) = tcSplitFunTys t_ty
245 %************************************************************************
247 \subsection{Miscellaneous}
249 %************************************************************************
252 ------------ Checking argument types for foreign import ----------------------
253 checkForeignArgs :: (Type -> Bool) -> [Type] -> TcM ()
254 checkForeignArgs pred tys
255 = mappM go tys `thenM_`
258 go ty = check (pred ty) (illegalForeignTyErr argument ty)
260 ------------ Checking result types for foreign calls ----------------------
261 -- Check that the type has the form
262 -- (IO t) or (t) , and that t satisfies the given predicate.
264 checkForeignRes :: Bool -> (Type -> Bool) -> Type -> TcM ()
269 checkForeignRes non_io_result_ok pred_res_ty ty
270 = case tcSplitTyConApp_maybe ty of
272 | io `hasKey` ioTyConKey && pred_res_ty res_ty
275 -> check (non_io_result_ok && pred_res_ty ty)
276 (illegalForeignTyErr result ty)
280 checkDotnet HscILX = Nothing
281 #if defined(mingw32_TARGET_OS)
282 checkDotnet HscC = Nothing
283 checkDotnet _ = Just (text "requires C code generation (-fvia-C)")
285 checkDotnet other = Just (text "requires .NET support (-filx or win32)")
288 checkCOrAsm HscC = Nothing
289 checkCOrAsm HscAsm = Nothing
291 = Just (text "requires via-C or native code generation (-fvia-C)")
293 checkCOrAsmOrInterp HscC = Nothing
294 checkCOrAsmOrInterp HscAsm = Nothing
295 checkCOrAsmOrInterp HscInterpreted = Nothing
296 checkCOrAsmOrInterp other
297 = Just (text "requires interpreted, C or native 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 = getDOpts `thenM` \ dflags ->
308 let hscLang = dopt_HscLang dflags in
310 HscNothing -> returnM ()
312 case check hscLang of
313 Nothing -> returnM ()
314 Just err -> addErrTc (text "Illegal foreign declaration:" <+> err)
320 check :: Bool -> Message -> TcM ()
321 check True _ = returnM ()
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:"))
342 = ptext SLIT("'This pointer' expected as last argument")