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.
21 #include "HsVersions.h"
50 isForeignImport :: LForeignDecl name -> Bool
51 isForeignImport (L _ (ForeignImport _ _ _)) = True
52 isForeignImport _ = False
55 isForeignExport :: LForeignDecl name -> Bool
56 isForeignExport (L _ (ForeignExport _ _ _)) = True
57 isForeignExport _ = False
60 %************************************************************************
64 %************************************************************************
67 tcForeignImports :: [LForeignDecl Name] -> TcM ([Id], [LForeignDecl Id])
68 tcForeignImports decls
69 = mapAndUnzipM (wrapLocSndM tcFImport) (filter isForeignImport decls)
71 tcFImport :: ForeignDecl Name -> TcM (Id, ForeignDecl Id)
72 tcFImport fo@(ForeignImport (L loc nm) hs_ty imp_decl)
73 = addErrCtxt (foreignDeclCtxt fo) $ do
74 sig_ty <- tcHsSigType (ForSigCtxt nm) hs_ty
76 -- drop the foralls before inspecting the structure
77 -- of the foreign type.
78 (_, t_ty) = tcSplitForAllTys sig_ty
79 (arg_tys, res_ty) = tcSplitFunTys t_ty
80 id = mkLocalId nm sig_ty
81 -- Use a LocalId to obey the invariant that locally-defined
82 -- things are LocalIds. However, it does not need zonking,
83 -- (so TcHsSyn.zonkForeignExports ignores it).
85 imp_decl' <- tcCheckFIType sig_ty arg_tys res_ty imp_decl
86 -- can't use sig_ty here because it :: Type and we need HsType Id
87 -- hence the undefined
88 return (id, ForeignImport (L loc id) undefined imp_decl')
89 tcFImport d = pprPanic "tcFImport" (ppr d)
93 ------------ Checking types for foreign import ----------------------
95 tcCheckFIType :: Type -> [Type] -> Type -> ForeignImport -> TcM ForeignImport
96 tcCheckFIType _ arg_tys res_ty (DNImport spec) = do
99 checkForeignArgs (isFFIDotnetTy dflags) arg_tys
100 checkForeignRes True{-non IO ok-} (isFFIDotnetTy dflags) res_ty
101 let (DNCallSpec isStatic kind _ _ _ _) = spec
103 DNMethod | not isStatic ->
105 [] -> addErrTc illegalDNMethodSig
107 | not (isFFIDotnetObjTy (last arg_tys)) -> addErrTc illegalDNMethodSig
108 | otherwise -> return ()
110 return (DNImport (withDNTypes spec (map toDNType arg_tys) (toDNType res_ty)))
112 tcCheckFIType sig_ty _ _ idecl@(CImport _ _ _ _ (CLabel _)) = do
114 check (isFFILabelTy sig_ty) (illegalForeignTyErr empty sig_ty)
117 tcCheckFIType sig_ty arg_tys res_ty idecl@(CImport cconv _ _ _ CWrapper) = do
118 -- Foreign wrapper (former f.e.d.)
119 -- The type must be of the form ft -> IO (FunPtr ft), where ft is a
120 -- valid foreign type. For legacy reasons ft -> IO (Ptr ft) as well
121 -- as ft -> IO Addr is accepted, too. The use of the latter two forms
122 -- is DEPRECATED, though.
123 checkCg checkCOrAsmOrInterp
126 [arg1_ty] -> do checkForeignArgs isFFIExternalTy arg1_tys
127 checkForeignRes nonIOok isFFIExportResultTy res1_ty
128 checkForeignRes mustBeIO isFFIDynResultTy res_ty
129 checkFEDArgs arg1_tys
131 (arg1_tys, res1_ty) = tcSplitFunTys arg1_ty
132 _ -> addErrTc (illegalForeignTyErr empty sig_ty)
135 tcCheckFIType sig_ty arg_tys res_ty idecl@(CImport cconv safety _ _ (CFunction target))
136 | isDynamicTarget target = do -- Foreign import dynamic
137 checkCg checkCOrAsmOrInterp
139 case arg_tys of -- The first arg must be Ptr, FunPtr, or Addr
141 check False (illegalForeignTyErr empty sig_ty)
143 (arg1_ty:arg_tys) -> do
145 check (isFFIDynArgumentTy arg1_ty)
146 (illegalForeignTyErr argument arg1_ty)
147 checkForeignArgs (isFFIArgumentTy dflags safety) arg_tys
148 checkForeignRes nonIOok (isFFIImportResultTy dflags) res_ty
150 | otherwise = do -- Normal foreign import
151 checkCg (checkCOrAsmOrDotNetOrInterp)
155 checkForeignArgs (isFFIArgumentTy dflags safety) arg_tys
156 checkForeignRes nonIOok (isFFIImportResultTy dflags) res_ty
157 checkMissingAmpersand dflags arg_tys res_ty
160 -- This makes a convenient place to check
161 -- that the C identifier is valid for C
162 checkCTarget :: CCallTarget -> TcM ()
163 checkCTarget (StaticTarget str) = do
164 checkCg checkCOrAsmOrDotNetOrInterp
165 check (isCLabelString str) (badCName str)
166 checkCTarget DynamicTarget = panic "checkCTarget DynamicTarget"
168 checkMissingAmpersand :: DynFlags -> [Type] -> Type -> TcM ()
169 checkMissingAmpersand dflags arg_tys res_ty
170 | null arg_tys && isFunPtrTy res_ty &&
171 dopt Opt_WarnDodgyForeignImports dflags
172 = addWarn (ptext (sLit "possible missing & in foreign import of FunPtr"))
177 On an Alpha, with foreign export dynamic, due to a giant hack when
178 building adjustor thunks, we only allow 4 integer arguments with
179 foreign export dynamic (i.e., 32 bytes of arguments after padding each
180 argument to a quadword, excluding floating-point arguments).
182 The check is needed for both via-C and native-code routes
185 #include "nativeGen/NCG.h"
187 checkFEDArgs :: [Type] -> TcM ()
188 #if alpha_TARGET_ARCH
190 = check (integral_args <= 32) err
192 integral_args = sum [ (machRepByteWidth . argMachRep . primRepToCgRep) prim_rep
193 | prim_rep <- map typePrimRep arg_tys,
194 primRepHint prim_rep /= FloatHint ]
195 err = ptext (sLit "On Alpha, I can only handle 32 bytes of non-floating-point arguments to foreign export dynamic")
197 checkFEDArgs _ = return ()
202 %************************************************************************
206 %************************************************************************
209 tcForeignExports :: [LForeignDecl Name]
210 -> TcM (LHsBinds TcId, [LForeignDecl TcId])
211 tcForeignExports decls
212 = foldlM combine (emptyLHsBinds, []) (filter isForeignExport decls)
214 combine (binds, fs) fe = do
215 (b, f) <- wrapLocSndM tcFExport fe
216 return (b `consBag` binds, f:fs)
218 tcFExport :: ForeignDecl Name -> TcM (LHsBind Id, ForeignDecl Id)
219 tcFExport fo@(ForeignExport (L loc nm) hs_ty spec) =
220 addErrCtxt (foreignDeclCtxt fo) $ do
222 sig_ty <- tcHsSigType (ForSigCtxt nm) hs_ty
223 rhs <- tcPolyExpr (nlHsVar nm) sig_ty
225 tcCheckFEType sig_ty spec
227 -- we're exporting a function, but at a type possibly more
228 -- constrained than its declared/inferred type. Hence the need
229 -- to create a local binding which will call the exported function
230 -- at a particular type (and, maybe, overloading).
233 -- We need to give a name to the new top-level binding that
234 -- is *stable* (i.e. the compiler won't change it later),
235 -- because this name will be referred to by the C code stub.
236 id <- mkStableIdFromName nm sig_ty loc mkForeignExportOcc
237 return (L loc (VarBind id rhs), ForeignExport (L loc id) undefined spec)
238 tcFExport d = pprPanic "tcFExport" (ppr d)
241 ------------ Checking argument types for foreign export ----------------------
244 tcCheckFEType :: Type -> ForeignExport -> TcM ()
245 tcCheckFEType sig_ty (CExport (CExportStatic str _)) = do
246 check (isCLabelString str) (badCName str)
247 checkForeignArgs isFFIExternalTy arg_tys
248 checkForeignRes nonIOok isFFIExportResultTy res_ty
250 -- Drop the foralls before inspecting n
251 -- the structure of the foreign type.
252 (_, t_ty) = tcSplitForAllTys sig_ty
253 (arg_tys, res_ty) = tcSplitFunTys t_ty
254 tcCheckFEType _ d = pprPanic "tcCheckFEType" (ppr d)
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 ()
279 nonIOok, mustBeIO :: Bool
283 checkForeignRes non_io_result_ok pred_res_ty ty
284 -- (IO t) is ok, and so is any newtype wrapping thereof
285 | Just (_, res_ty, _) <- tcSplitIOType_maybe ty,
290 = check (non_io_result_ok && pred_res_ty ty)
291 (illegalForeignTyErr result ty)
295 checkDotnet :: HscTarget -> Maybe SDoc
296 #if defined(mingw32_TARGET_OS)
297 checkDotnet HscC = Nothing
298 checkDotnet _ = Just (text "requires C code generation (-fvia-C)")
300 checkDotnet _ = Just (text "requires .NET support (-filx or win32)")
303 checkCOrAsm :: HscTarget -> Maybe SDoc
304 checkCOrAsm HscC = Nothing
305 checkCOrAsm HscAsm = Nothing
307 = Just (text "requires via-C or native code generation (-fvia-C)")
309 checkCOrAsmOrInterp :: HscTarget -> Maybe SDoc
310 checkCOrAsmOrInterp HscC = Nothing
311 checkCOrAsmOrInterp HscAsm = Nothing
312 checkCOrAsmOrInterp HscInterpreted = Nothing
313 checkCOrAsmOrInterp _
314 = Just (text "requires interpreted, C or native code generation")
316 checkCOrAsmOrDotNetOrInterp :: HscTarget -> Maybe SDoc
317 checkCOrAsmOrDotNetOrInterp HscC = Nothing
318 checkCOrAsmOrDotNetOrInterp HscAsm = Nothing
319 checkCOrAsmOrDotNetOrInterp HscInterpreted = Nothing
320 checkCOrAsmOrDotNetOrInterp _
321 = Just (text "requires interpreted, C or native code generation")
323 checkCg :: (HscTarget -> Maybe SDoc) -> TcM ()
326 let target = hscTarget dflags
328 HscNothing -> return ()
332 Just err -> addErrTc (text "Illegal foreign declaration:" <+> err)
338 checkCConv :: CCallConv -> TcM ()
339 checkCConv CCallConv = return ()
341 checkCConv StdCallConv = return ()
343 checkCConv StdCallConv = addErrTc (text "calling convention not supported on this architecture: stdcall")
345 checkCConv CmmCallConv = panic "checkCConv CmmCallConv"
351 check :: Bool -> Message -> TcM ()
352 check True _ = return ()
353 check _ the_err = addErrTc the_err
355 illegalForeignTyErr :: SDoc -> Type -> SDoc
356 illegalForeignTyErr arg_or_res ty
357 = hang (hsep [ptext (sLit "Unacceptable"), arg_or_res,
358 ptext (sLit "type in foreign declaration:")])
361 -- Used for 'arg_or_res' argument to illegalForeignTyErr
362 argument, result :: SDoc
363 argument = text "argument"
364 result = text "result"
366 badCName :: CLabelString -> Message
368 = sep [quotes (ppr target) <+> ptext (sLit "is not a valid C identifier")]
370 foreignDeclCtxt :: ForeignDecl Name -> SDoc
372 = hang (ptext (sLit "When checking declaration:"))
375 illegalDNMethodSig :: SDoc
377 = ptext (sLit "'This pointer' expected as last argument")