2 % (c) The University of Glasgow 2006
3 % (c) The AQUA Project, Glasgow University, 1998
5 \section[TcForeign]{Typechecking \tr{foreign} declarations}
7 A foreign declaration is used to either give an externally
8 implemented function a Haskell type (and calling interface) or
9 give a Haskell function an external calling interface. Either way,
10 the range of argument and result types these functions can accommodate
11 is restricted to what the outside world understands (read C), and this
12 module checks to see if a foreign declaration has got a legal type.
16 -- The above warning supression flag is a temporary kludge.
17 -- While working on this module you are encouraged to remove it and fix
18 -- any warnings in the module. See
19 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
28 #include "HsVersions.h"
56 isForeignImport :: LForeignDecl name -> Bool
57 isForeignImport (L _ (ForeignImport _ _ _)) = True
58 isForeignImport _ = False
61 isForeignExport :: LForeignDecl name -> Bool
62 isForeignExport (L _ (ForeignExport _ _ _)) = True
63 isForeignExport _ = False
66 %************************************************************************
70 %************************************************************************
73 tcForeignImports :: [LForeignDecl Name] -> TcM ([Id], [LForeignDecl Id])
74 tcForeignImports decls
75 = mapAndUnzipM (wrapLocSndM tcFImport) (filter isForeignImport decls)
77 tcFImport :: ForeignDecl Name -> TcM (Id, ForeignDecl Id)
78 tcFImport fo@(ForeignImport (L loc nm) hs_ty imp_decl)
79 = addErrCtxt (foreignDeclCtxt fo) $ do
80 sig_ty <- tcHsSigType (ForSigCtxt nm) hs_ty
82 -- drop the foralls before inspecting the structure
83 -- of the foreign type.
84 (_, t_ty) = tcSplitForAllTys sig_ty
85 (arg_tys, res_ty) = tcSplitFunTys t_ty
86 id = mkLocalId nm sig_ty
87 -- Use a LocalId to obey the invariant that locally-defined
88 -- things are LocalIds. However, it does not need zonking,
89 -- (so TcHsSyn.zonkForeignExports ignores it).
91 imp_decl' <- tcCheckFIType sig_ty arg_tys res_ty imp_decl
92 -- can't use sig_ty here because it :: Type and we need HsType Id
93 -- hence the undefined
94 return (id, ForeignImport (L loc id) undefined imp_decl')
98 ------------ Checking types for foreign import ----------------------
100 tcCheckFIType _ arg_tys res_ty (DNImport spec) = do
103 checkForeignArgs (isFFIDotnetTy dflags) arg_tys
104 checkForeignRes True{-non IO ok-} (isFFIDotnetTy dflags) res_ty
105 let (DNCallSpec isStatic kind _ _ _ _) = spec
107 DNMethod | not isStatic ->
109 [] -> addErrTc illegalDNMethodSig
111 | not (isFFIDotnetObjTy (last arg_tys)) -> addErrTc illegalDNMethodSig
112 | otherwise -> return ()
114 return (DNImport (withDNTypes spec (map toDNType arg_tys) (toDNType res_ty)))
116 tcCheckFIType sig_ty arg_tys res_ty idecl@(CImport _ _ _ _ (CLabel _)) = do
118 check (isFFILabelTy sig_ty) (illegalForeignTyErr empty sig_ty)
121 tcCheckFIType sig_ty arg_tys res_ty idecl@(CImport cconv _ _ _ CWrapper) = do
122 -- Foreign wrapper (former f.e.d.)
123 -- The type must be of the form ft -> IO (FunPtr ft), where ft is a
124 -- valid foreign type. For legacy reasons ft -> IO (Ptr ft) as well
125 -- as ft -> IO Addr is accepted, too. The use of the latter two forms
126 -- is DEPRECATED, though.
127 checkCg checkCOrAsmOrInterp
130 [arg1_ty] -> do checkForeignArgs isFFIExternalTy arg1_tys
131 checkForeignRes nonIOok isFFIExportResultTy res1_ty
132 checkForeignRes mustBeIO isFFIDynResultTy res_ty
133 checkFEDArgs arg1_tys
135 (arg1_tys, res1_ty) = tcSplitFunTys arg1_ty
136 other -> addErrTc (illegalForeignTyErr empty sig_ty)
139 tcCheckFIType sig_ty arg_tys res_ty idecl@(CImport cconv safety _ _ (CFunction target))
140 | isDynamicTarget target = do -- Foreign import dynamic
141 checkCg checkCOrAsmOrInterp
143 case arg_tys of -- The first arg must be Ptr, FunPtr, or Addr
145 check False (illegalForeignTyErr empty sig_ty)
147 (arg1_ty:arg_tys) -> do
149 check (isFFIDynArgumentTy arg1_ty)
150 (illegalForeignTyErr argument arg1_ty)
151 checkForeignArgs (isFFIArgumentTy dflags safety) arg_tys
152 checkForeignRes nonIOok (isFFIImportResultTy dflags) res_ty
154 | otherwise = do -- Normal foreign import
155 checkCg (checkCOrAsmOrDotNetOrInterp)
159 checkForeignArgs (isFFIArgumentTy dflags safety) arg_tys
160 checkForeignRes nonIOok (isFFIImportResultTy dflags) res_ty
163 -- This makes a convenient place to check
164 -- that the C identifier is valid for C
165 checkCTarget (StaticTarget str) = do
166 checkCg checkCOrAsmOrDotNetOrInterp
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 . argMachRep . primRepToCgRep) prim_rep
184 | prim_rep <- map typePrimRep arg_tys,
185 primRepHint prim_rep /= FloatHint ]
186 err = ptext SLIT("On Alpha, I can only handle 32 bytes of non-floating-point arguments to foreign export dynamic")
188 checkFEDArgs arg_tys = return ()
193 %************************************************************************
197 %************************************************************************
200 tcForeignExports :: [LForeignDecl Name]
201 -> TcM (LHsBinds TcId, [LForeignDecl TcId])
202 tcForeignExports decls
203 = foldlM combine (emptyLHsBinds, []) (filter isForeignExport decls)
205 combine (binds, fs) fe = do
206 (b, f) <- wrapLocSndM tcFExport fe
207 return (b `consBag` binds, f:fs)
209 tcFExport :: ForeignDecl Name -> TcM (LHsBind Id, ForeignDecl Id)
210 tcFExport fo@(ForeignExport (L loc nm) hs_ty spec) =
211 addErrCtxt (foreignDeclCtxt fo) $ do
213 sig_ty <- tcHsSigType (ForSigCtxt nm) hs_ty
214 rhs <- tcPolyExpr (nlHsVar nm) sig_ty
216 tcCheckFEType sig_ty spec
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).
226 -- We need to give a name to the new top-level binding that
227 -- is *stable* (i.e. the compiler won't change it later),
228 -- because this name will be referred to by the C code stub.
229 -- Furthermore, the name must be unique (see #1533). If the
230 -- same function is foreign-exported multiple times, the
231 -- top-level bindings generated must not have the same name.
232 -- Hence we create an External name (doesn't change), and we
233 -- append a Unique to the string right here.
234 uniq_str = showSDoc (pprUnique uniq)
235 occ = mkVarOcc (occNameString (getOccName nm) ++ '_' : uniq_str)
236 gnm = mkExternalName uniq mod (mkForeignExportOcc occ) loc
237 id = mkExportedLocalId gnm sig_ty
238 bind = L loc (VarBind id rhs)
240 return (bind, ForeignExport (L loc id) undefined spec)
243 ------------ Checking argument types for foreign export ----------------------
246 tcCheckFEType sig_ty (CExport (CExportStatic str _)) = do
247 check (isCLabelString str) (badCName str)
248 checkForeignArgs isFFIExternalTy arg_tys
249 checkForeignRes nonIOok isFFIExportResultTy res_ty
251 -- Drop the foralls before inspecting n
252 -- the structure of the foreign type.
253 (_, t_ty) = tcSplitForAllTys sig_ty
254 (arg_tys, res_ty) = tcSplitFunTys t_ty
259 %************************************************************************
261 \subsection{Miscellaneous}
263 %************************************************************************
266 ------------ Checking argument types for foreign import ----------------------
267 checkForeignArgs :: (Type -> Bool) -> [Type] -> TcM ()
268 checkForeignArgs pred tys
271 go ty = check (pred ty) (illegalForeignTyErr argument ty)
273 ------------ Checking result types for foreign calls ----------------------
274 -- Check that the type has the form
275 -- (IO t) or (t) , and that t satisfies the given predicate.
277 checkForeignRes :: Bool -> (Type -> Bool) -> Type -> TcM ()
282 checkForeignRes non_io_result_ok pred_res_ty ty
283 -- (IO t) is ok, and so is any newtype wrapping thereof
284 | Just (io, res_ty, _) <- tcSplitIOType_maybe ty,
289 = check (non_io_result_ok && pred_res_ty ty)
290 (illegalForeignTyErr result ty)
294 #if defined(mingw32_TARGET_OS)
295 checkDotnet HscC = Nothing
296 checkDotnet _ = Just (text "requires C code generation (-fvia-C)")
298 checkDotnet other = Just (text "requires .NET support (-filx or win32)")
301 checkCOrAsm HscC = Nothing
302 checkCOrAsm HscAsm = Nothing
304 = Just (text "requires via-C or native code generation (-fvia-C)")
306 checkCOrAsmOrInterp HscC = Nothing
307 checkCOrAsmOrInterp HscAsm = Nothing
308 checkCOrAsmOrInterp HscInterpreted = Nothing
309 checkCOrAsmOrInterp other
310 = Just (text "requires interpreted, C or native code generation")
312 checkCOrAsmOrDotNetOrInterp HscC = Nothing
313 checkCOrAsmOrDotNetOrInterp HscAsm = Nothing
314 checkCOrAsmOrDotNetOrInterp HscInterpreted = Nothing
315 checkCOrAsmOrDotNetOrInterp other
316 = Just (text "requires interpreted, C or native code generation")
320 let target = hscTarget dflags
322 HscNothing -> return ()
326 Just err -> addErrTc (text "Illegal foreign declaration:" <+> err)
332 checkCConv :: CCallConv -> TcM ()
333 checkCConv CCallConv = return ()
335 checkCConv StdCallConv = return ()
337 checkCConv StdCallConv = addErrTc (text "calling convention not supported on this architecture: stdcall")
344 check :: Bool -> Message -> TcM ()
345 check True _ = return ()
346 check _ the_err = addErrTc the_err
348 illegalForeignTyErr arg_or_res ty
349 = hang (hsep [ptext SLIT("Unacceptable"), arg_or_res,
350 ptext SLIT("type in foreign declaration:")])
353 -- Used for 'arg_or_res' argument to illegalForeignTyErr
354 argument = text "argument"
355 result = text "result"
357 badCName :: CLabelString -> Message
359 = sep [quotes (ppr target) <+> ptext SLIT("is not a valid C identifier")]
362 = hang (ptext SLIT("When checking declaration:"))
366 = ptext SLIT("'This pointer' expected as last argument")