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(..), FoImport(..), FoExport(..)
25 import RnHsSyn ( RenamedHsDecl, RenamedForeignDecl )
28 import TcEnv ( newLocalId )
29 import TcMonoType ( tcHsLiftedSigType )
30 import TcHsSyn ( TcMonoBinds, TypecheckedForeignDecl,
32 import TcExpr ( tcPolyExpr )
33 import Inst ( emptyLIE, LIE, plusLIE )
35 import ErrUtils ( Message )
36 import Id ( Id, mkLocalId )
37 import Name ( nameOccName )
38 import TysWiredIn ( isFFIArgumentTy, isFFIImportResultTy,
40 isFFIExternalTy, isFFIDynArgumentTy, isFFIDynResultTy,
43 import TcType ( Type, tcSplitFunTys, tcSplitTyConApp_maybe, tcSplitForAllTys )
44 import ForeignCall ( CCallSpec(..), CExportSpec(..), CCallTarget(..), isDynamicTarget, isCasmTarget )
45 import CStrings ( CLabelString, isCLabelString )
46 import PrelNames ( hasKey, ioTyConKey )
47 import CmdLineOpts ( dopt_HscLang, HscLang(..) )
54 isForeignImport :: ForeignDecl name -> Bool
55 isForeignImport (ForeignImport _ _ _ _) = True
56 isForeignImport _ = False
59 isForeignExport :: ForeignDecl name -> Bool
60 isForeignExport (ForeignExport _ _ _ _) = True
61 isForeignExport _ = False
64 %************************************************************************
68 %************************************************************************
71 tcForeignImports :: [RenamedHsDecl] -> TcM ([Id], [TypecheckedForeignDecl])
72 tcForeignImports decls =
73 mapAndUnzipTc tcFImport [ foreign_decl | ForD foreign_decl <- decls, isForeignImport foreign_decl]
75 tcFImport :: RenamedForeignDecl -> TcM (Id, TypecheckedForeignDecl)
76 tcFImport fo@(ForeignImport nm hs_ty imp_decl src_loc)
77 = tcAddSrcLoc src_loc $
78 tcAddErrCtxt (foreignDeclCtxt fo) $
79 tcHsLiftedSigType hs_ty `thenTc` \ sig_ty ->
81 -- drop the foralls before inspecting the structure
82 -- of the foreign type.
83 (_, t_ty) = tcSplitForAllTys sig_ty
84 (arg_tys, res_ty) = tcSplitFunTys t_ty
85 id = mkLocalId nm sig_ty
87 tcCheckFIType sig_ty arg_tys res_ty imp_decl `thenNF_Tc_`
88 returnTc (id, ForeignImport id undefined imp_decl src_loc)
92 ------------ Checking types for foreign import ----------------------
94 tcCheckFIType _ _ _ (DNImport _)
97 tcCheckFIType sig_ty arg_tys res_ty (LblImport _)
98 = checkCg checkCOrAsm `thenNF_Tc_`
99 check (isFFILabelTy sig_ty) (illegalForeignTyErr empty sig_ty)
101 tcCheckFIType sig_ty arg_tys res_ty (CDynImport _)
102 = -- Foreign export dynamic
103 -- The first (and only!) arg has got to be a function type
104 -- and it must return IO t; result type is IO Addr
105 checkCg checkCOrAsm `thenNF_Tc_`
107 [arg1_ty] -> checkForeignArgs isFFIExternalTy arg1_tys `thenNF_Tc_`
108 checkForeignRes nonIOok isFFIExportResultTy res1_ty `thenNF_Tc_`
109 checkForeignRes mustBeIO isFFIDynResultTy res_ty
111 (arg1_tys, res1_ty) = tcSplitFunTys arg1_ty
112 other -> addErrTc (illegalForeignTyErr empty sig_ty)
114 tcCheckFIType sig_ty arg_tys res_ty (CImport (CCallSpec target _ safety))
115 | isDynamicTarget target -- Foreign import dynamic
116 = checkCg checkCOrAsm `thenNF_Tc_`
117 case arg_tys of -- The first arg must be Addr
118 [] -> check False (illegalForeignTyErr empty sig_ty)
119 (arg1_ty:arg_tys) -> getDOptsTc `thenNF_Tc` \ dflags ->
120 check (isFFIDynArgumentTy arg1_ty)
121 (illegalForeignTyErr argument arg1_ty) `thenNF_Tc_`
122 checkForeignArgs (isFFIArgumentTy dflags safety) arg_tys `thenNF_Tc_`
123 checkForeignRes nonIOok (isFFIImportResultTy dflags) res_ty
125 | otherwise -- Normal foreign import
126 = checkCg (if isCasmTarget target
127 then checkC else checkCOrAsmOrDotNet) `thenNF_Tc_`
128 checkCTarget target `thenNF_Tc_`
129 getDOptsTc `thenNF_Tc` \ dflags ->
130 checkForeignArgs (isFFIArgumentTy dflags safety) arg_tys `thenNF_Tc_`
131 checkForeignRes nonIOok (isFFIImportResultTy dflags) res_ty
133 -- This makes a convenient place to check
134 -- that the C identifier is valid for C
135 checkCTarget (StaticTarget str)
136 = checkCg checkCOrAsmOrDotNet `thenNF_Tc_`
137 check (isCLabelString str) (badCName str)
139 checkCTarget (CasmTarget _)
144 %************************************************************************
148 %************************************************************************
151 tcForeignExports :: [RenamedHsDecl] -> TcM (LIE, TcMonoBinds, [TcForeignExportDecl])
152 tcForeignExports decls =
153 foldlTc combine (emptyLIE, EmptyMonoBinds, [])
154 [ foreign_decl | ForD foreign_decl <- decls, isForeignExport foreign_decl]
156 combine (lie, binds, fs) fe =
157 tcFExport fe `thenTc ` \ (a_lie, b, f) ->
158 returnTc (lie `plusLIE` a_lie, b `AndMonoBinds` binds, f:fs)
160 tcFExport :: RenamedForeignDecl -> TcM (LIE, TcMonoBinds, TcForeignExportDecl)
161 tcFExport fo@(ForeignExport nm hs_ty spec src_loc) =
162 tcAddSrcLoc src_loc $
163 tcAddErrCtxt (foreignDeclCtxt fo) $
165 tcHsLiftedSigType hs_ty `thenTc` \ sig_ty ->
166 tcPolyExpr (HsVar nm) sig_ty `thenTc` \ (rhs, lie, _, _, _) ->
168 tcCheckFEType sig_ty spec `thenTc_`
170 -- we're exporting a function, but at a type possibly more constrained
171 -- than its declared/inferred type. Hence the need
172 -- to create a local binding which will call the exported function
173 -- at a particular type (and, maybe, overloading).
174 newLocalId (nameOccName nm) sig_ty src_loc `thenNF_Tc` \ id ->
176 bind = VarMonoBind id rhs
178 returnTc (lie, bind, ForeignExport id undefined spec src_loc)
181 ------------ Checking argument types for foreign export ----------------------
184 tcCheckFEType sig_ty (CExport (CExportStatic str _))
185 = check (isCLabelString str) (badCName str) `thenNF_Tc_`
186 checkForeignArgs isFFIExternalTy arg_tys `thenNF_Tc_`
187 checkForeignRes nonIOok isFFIExportResultTy res_ty
189 -- Drop the foralls before inspecting n
190 -- the structure of the foreign type.
191 (_, t_ty) = tcSplitForAllTys sig_ty
192 (arg_tys, res_ty) = tcSplitFunTys t_ty
197 %************************************************************************
199 \subsection{Miscellaneous}
201 %************************************************************************
204 ------------ Checking argument types for foreign import ----------------------
205 checkForeignArgs :: (Type -> Bool) -> [Type] -> NF_TcM ()
206 checkForeignArgs pred tys
207 = mapNF_Tc go tys `thenNF_Tc_` returnNF_Tc ()
209 go ty = check (pred ty) (illegalForeignTyErr argument ty)
212 ------------ Checking result types for foreign calls ----------------------
213 -- Check that the type has the form
214 -- (IO t) or (t) , and that t satisfies the given predicate.
216 checkForeignRes :: Bool -> (Type -> Bool) -> Type -> NF_TcM ()
221 checkForeignRes non_io_result_ok pred_res_ty ty
222 = case tcSplitTyConApp_maybe ty of
224 | io `hasKey` ioTyConKey && pred_res_ty res_ty
227 -> check (non_io_result_ok && pred_res_ty ty)
228 (illegalForeignTyErr result ty)
232 checkDotNet HscILX = Nothing
233 checkDotNet other = Just (text "requires .NET code generation (-filx)")
235 checkC HscC = Nothing
236 checkC other = Just (text "requires C code generation (-fvia-C)")
238 checkCOrAsm HscC = Nothing
239 checkCOrAsm HscAsm = Nothing
240 checkCOrAsm other = Just (text "via-C or native code generation (-fvia-C)")
242 checkCOrAsmOrDotNet HscC = Nothing
243 checkCOrAsmOrDotNet HscAsm = Nothing
244 checkCOrAsmOrDotNet HscILX = Nothing
245 checkCOrAsmOrDotNet other = Just (text "requires C, native or .NET ILX code generation")
248 = getDOptsTc `thenNF_Tc` \ dflags ->
249 case check (dopt_HscLang dflags) of
250 Nothing -> returnNF_Tc ()
251 Just err -> addErrTc (text "Illegal foreign declaration:" <+> err)
257 check :: Bool -> Message -> NF_TcM ()
258 check True _ = returnTc ()
259 check _ the_err = addErrTc the_err
261 illegalForeignTyErr arg_or_res ty
262 = hang (hsep [ptext SLIT("Unacceptable"), arg_or_res, ptext SLIT("type in foreign declaration:")])
265 -- Used for 'arg_or_res' argument to illegalForeignTyErr
266 argument = text "argument"
267 result = text "result"
269 badCName :: CLabelString -> Message
270 badCName target = sep [quotes (ppr target) <+> ptext SLIT("is not a valid C identifier")]
273 = hang (ptext SLIT("When checking declaration:"))