2 % (c) The AQUA Project, Glasgow University, 1998
4 \section[DsCCall]{Desugaring \tr{foreign} declarations}
6 Expanding out @foreign import@ and @foreign export@ declarations.
9 module DsForeign ( dsForeigns ) where
11 #include "HsVersions.h"
15 import DsCCall ( dsCCall, boxResult, unboxArg, wrapUnboxedValue )
19 import HsSyn ( ExtName(..), ForeignDecl(..), isDynamic, ForKind(..) )
21 import TcHsSyn ( TypecheckedForeignDecl )
22 import CoreUtils ( coreExprType )
23 import Const ( Con(..), mkMachInt )
24 import DataCon ( DataCon, dataConId )
25 import Id ( Id, idType, idName,
28 import Const ( Literal(..) )
29 import Name ( getOccString, NamedThing(..) )
30 import PrelVals ( realWorldPrimId )
31 import PrelInfo ( deRefStablePtr_NAME, bindIO_NAME, makeStablePtr_NAME )
32 import Type ( splitAlgTyConApp_maybe,
33 splitTyConApp_maybe, splitFunTys, splitForAllTys,
34 Type, mkFunTys, mkForAllTys, mkTyConApp,
35 mkTyVarTy, mkFunTy, splitAppTy
37 import PrimOp ( PrimOp(..) )
39 import TysPrim ( realWorldStatePrimTy, addrPrimTy )
40 import TysWiredIn ( unitTyCon, addrTy, stablePtrTyCon,
41 unboxedTupleCon, addrDataCon
47 Desugaring of @foreign@ declarations is naturally split up into
48 parts, an @import@ and an @export@ part. A @foreign import@
51 foreign import cc nm f :: prim_args -> IO prim_res
55 f :: prim_args -> IO prim_res
56 f a1 ... an = _ccall_ nm cc a1 ... an
58 so we reuse the desugaring code in @DsCCall@ to deal with these.
61 dsForeigns :: [TypecheckedForeignDecl]
62 -> DsM ( [CoreBind] -- desugared foreign imports
63 , [CoreBind] -- helper functions for foreign exports
64 , SDoc -- Header file prototypes for "foreign exported" functions.
65 , SDoc -- C stubs to use when calling "foreign exported" funs.
67 dsForeigns fos = foldlDs combine ([],[],empty,empty) fos
69 combine (acc_fi, acc_fe, acc_h, acc_c) fo@(ForeignDecl i imp_exp _ ext_nm cconv _)
70 | isForeignImport = -- foreign import (dynamic)?
71 dsFImport i (idType i) uns ext_nm cconv `thenDs` \ b ->
72 returnDs (b:acc_fi, acc_fe, acc_h, acc_c)
74 dsFLabel i ext_nm `thenDs` \ b ->
75 returnDs (b:acc_fi, acc_fe, acc_h, acc_c)
77 dsFExportDynamic i (idType i) ext_nm cconv `thenDs` \ (fi,fe,h,c) ->
78 returnDs (fi:acc_fi, fe:acc_fe, h $$ acc_h, c $$ acc_c)
80 | otherwise = -- foreign export
81 dsFExport i (idType i) ext_nm cconv False `thenDs` \ (fe,h,c) ->
82 returnDs (acc_fi, fe:acc_fe, h $$ acc_h, c $$ acc_c)
94 (FoImport uns) = imp_exp
98 Desugaring foreign imports is just the matter of creating a binding
99 that on its RHS unboxes its arguments, performs the external call
100 (using the CCallOp primop), before boxing the result up and returning it.
104 -> Type -- Type of foreign import.
105 -> Bool -- True <=> might cause Haskell GC
109 dsFImport nm ty may_not_gc ext_name cconv =
110 newSysLocalDs realWorldStatePrimTy `thenDs` \ old_s ->
111 splitForeignTyDs ty `thenDs` \ (tvs, args, mbIoDataCon, io_res_ty) ->
114 | is_io_action = old_s
115 | otherwise = realWorldPrimId
117 arg_exprs = map (Var) args
124 mapAndUnzipDs unboxArg arg_exprs `thenDs` \ (unboxed_args, arg_wrappers) ->
125 (if not is_io_action then
126 newSysLocalDs realWorldStatePrimTy `thenDs` \ state_tok ->
127 wrapUnboxedValue io_res_ty `thenDs` \ (ccall_result_ty, v, res_v) ->
128 returnDs ( ccall_result_ty
129 , \ prim_app -> Case prim_app (mkWildId ccall_result_ty)
130 [(DataCon (unboxedTupleCon 2), [state_tok, v], res_v)])
132 boxResult io_res_ty) `thenDs` \ (final_result_ty, res_wrapper) ->
134 Dynamic -> getUniqueDs `thenDs` \ u ->
136 ExtName fs _ -> returnDs (Left fs)) `thenDs` \ label ->
138 val_args = Var the_state_arg : unboxed_args
139 final_args = Type inst_ty : val_args
141 -- A CCallOp has type (forall a. a), so we must instantiate
142 -- it at the full type, including the state argument
143 inst_ty = mkFunTys (map coreExprType val_args) final_result_ty
145 the_ccall_op = CCallOp label False (not may_not_gc) cconv
147 the_prim_app = mkPrimApp the_ccall_op (final_args :: [CoreArg])
149 body = foldr ($) (res_wrapper the_prim_app) arg_wrappers
152 | not is_io_action = body
153 | otherwise = Lam old_s body
155 newSysLocalDs (coreExprType the_body) `thenDs` \ ds ->
161 mkApps (Var (dataConId ioDataCon))
162 [Type io_res_ty, Var ds]
164 fo_rhs = mkLams (tvs ++ args)
165 (Let (NonRec ds (the_body::CoreExpr)) io_app)
167 returnDs (NonRec nm fo_rhs)
170 Given the type of a foreign import declaration, split it up into
171 its constituent parts.
174 splitForeignTyDs :: Type -> DsM ([TyVar], [Id], Maybe DataCon, Type)
175 splitForeignTyDs ty =
176 newSysLocalsDs arg_tys `thenDs` \ ds_args ->
177 case splitAlgTyConApp_maybe res_ty of
178 Just (_,(io_res_ty:_),(ioCon:_)) -> -- .... -> IO t
179 returnDs (tvs, ds_args, Just ioCon, io_res_ty)
181 returnDs (tvs, ds_args, Nothing, res_ty)
183 (arg_tys, res_ty) = splitFunTys sans_foralls
184 (tvs, sans_foralls) = splitForAllTys ty
191 dsFLabel :: Id -> ExtName -> DsM CoreBind
192 dsFLabel nm ext_name = returnDs (NonRec nm fo_rhs)
194 fo_rhs = mkConApp addrDataCon [mkLit (MachLitLit enm addrPrimTy)]
198 Dynamic -> panic "dsFLabel: Dynamic - shouldn't ever happen."
202 The function that does most of the work for 'foreign export' declarations.
203 (see below for the boilerplate code a 'foreign export' declaration expands
208 -> Type -- Type of foreign export.
211 -> Bool -- True => invoke IO action that's hanging off
212 -- the first argument's stable pointer
217 dsFExport i ty ext_name cconv isDyn =
218 newSysLocalDs helper_ty `thenDs` \ f_helper ->
219 newSysLocalsDs fe_arg_tys `thenDs` \ fe_args ->
221 newSysLocalDs stbl_ptr_ty `thenDs` \ stbl_ptr ->
222 newSysLocalDs stbl_ptr_to_ty `thenDs` \ stbl_value ->
223 dsLookupGlobalValue deRefStablePtr_NAME `thenDs` \ deRefStablePtrId ->
225 the_deref_app = mkApps (Var deRefStablePtrId)
226 [ Type stbl_ptr_to_ty, Var stbl_ptr ]
228 newSysLocalDs (coreExprType the_deref_app) `thenDs` \ x_deref_app ->
229 dsLookupGlobalValue bindIO_NAME `thenDs` \ bindIOId ->
230 newSysLocalDs (mkFunTy stbl_ptr_to_ty
231 (mkTyConApp ioTyCon [res_ty])) `thenDs` \ x_cont ->
234 bindNonRec x_cont (mkLams [stbl_value] cont) $
235 bindNonRec x_deref_app the_deref_app
236 (mkApps (Var bindIOId)
237 [ Type stbl_ptr_to_ty
242 returnDs (stbl_value, stbl_app, stbl_ptr)
246 panic "stbl_ptr" -- should never be touched.
247 )) `thenDs` \ (i, getFun_wrapper, stbl_ptr) ->
250 | isDyn = stbl_ptr:fe_args
251 | otherwise = fe_args
254 | isDyn = stbl_ptr_ty:helper_arg_tys
255 | otherwise = helper_arg_tys
259 mkApps (Var i) (map (Type . mkTyVarTy) tvs ++ map Var fe_args)
261 getModuleAndGroupDs `thenDs` \ (mod,_) ->
262 getUniqueDs `thenDs` \ uniq ->
264 the_body = mkLams (tvs ++ wrapper_args) the_app
269 Dynamic -> panic "dsFExport: Dynamic - shouldn't ever happen."
271 f_helper_glob = mkIdVisible mod uniq f_helper
272 (h_stub, c_stub) = fexportEntry c_nm f_helper_glob wrapper_arg_tys the_result_ty cconv
274 returnDs (NonRec f_helper_glob the_body, h_stub, c_stub)
278 (tvs,sans_foralls) = splitForAllTys ty
279 (fe_arg_tys', io_res) = splitFunTys sans_foralls
282 Just (ioTyCon, [res_ty]) = splitTyConApp_maybe io_res
284 (_, stbl_ptr_ty') = splitForAllTys stbl_ptr_ty
285 (_, stbl_ptr_to_ty) = splitAppTy stbl_ptr_ty'
288 | isDyn = tail fe_arg_tys'
289 | otherwise = fe_arg_tys'
291 (stbl_ptr_ty, helper_arg_tys) =
293 (x:xs) | isDyn -> (x,xs)
294 ls -> (error "stbl_ptr_ty", ls)
298 mkFunTys arg_tys io_res
301 | isDyn = stbl_ptr_ty : helper_arg_tys
302 | otherwise = helper_arg_tys
305 case splitTyConApp_maybe io_res of
307 case splitTyConApp_maybe res_ty of
308 Just (tc,_) | getUnique tc /= getUnique unitTyCon -> Just res_ty
314 "foreign export dynamic" lets you dress up Haskell IO actions
315 of some fixed type behind an externally callable interface (i.e.,
316 as a C function pointer). Useful for callbacks and stuff.
319 foreign export stdcall f :: (Addr -> Int -> IO Int) -> IO Addr
321 -- Haskell-visible constructor, which is generated from the
324 f :: (Addr -> Int -> IO Int) -> IO Addr
325 f cback = IO ( \ s1# ->
326 case makeStablePtr# cback s1# of { StateAndStablePtr# s2# sp# ->
327 case _ccall_ "mkAdjustor" sp# ``f_helper'' s2# of
328 StateAndAddr# s3# a# ->
338 foreign export "f_helper" f_helper :: StablePtr (Addr -> Int -> IO Int) -> Addr -> Int -> IO Int
339 -- `special' foreign export that invokes the closure pointed to by the
344 dsFExportDynamic :: Id
345 -> Type -- Type of foreign export.
348 -> DsM (CoreBind, CoreBind, SDoc, SDoc)
349 dsFExportDynamic i ty ext_name cconv =
350 newSysLocalDs ty `thenDs` \ fe_id ->
352 -- hack: need to get at the name of the C stub we're about to generate.
353 fe_nm = toCName fe_id
354 fe_ext_name = ExtName (_PK_ fe_nm) Nothing
356 dsFExport i export_ty fe_ext_name cconv True `thenDs` \ (fe@(NonRec fe_helper fe_expr), h_code, c_code) ->
357 newSysLocalDs arg_ty `thenDs` \ cback ->
358 dsLookupGlobalValue makeStablePtr_NAME `thenDs` \ makeStablePtrId ->
360 mk_stbl_ptr_app = mkApps (Var makeStablePtrId) [ Type arg_ty, Var cback ]
361 mk_stbl_ptr_app_ty = coreExprType mk_stbl_ptr_app
363 newSysLocalDs mk_stbl_ptr_app_ty `thenDs` \ x_mk_stbl_ptr_app ->
364 dsLookupGlobalValue bindIO_NAME `thenDs` \ bindIOId ->
365 newSysLocalDs (mkTyConApp stablePtrTyCon [arg_ty]) `thenDs` \ stbl_value ->
367 stbl_app = \ x_cont cont ret_ty ->
368 bindNonRec x_cont cont $
369 bindNonRec x_mk_stbl_ptr_app mk_stbl_ptr_app $
370 (mkApps (Var bindIOId)
371 [ Type (mkTyConApp stablePtrTyCon [arg_ty])
373 , Var x_mk_stbl_ptr_app
378 The arguments to the external function which will
379 create a little bit of (template) code on the fly
380 for allowing the (stable pointed) Haskell closure
381 to be entered using an external calling convention
384 adj_args = [ mkLit (mkMachInt (fromInt (callConvToInt cconv)))
386 , mkLit (MachLitLit (_PK_ fe_nm) addrPrimTy)
388 -- name of external entry point providing these services.
389 -- (probably in the RTS.)
390 adjustor = SLIT("createAdjustor")
392 dsCCall adjustor adj_args False False addrTy `thenDs` \ ccall_adj ->
393 let ccall_adj_ty = coreExprType ccall_adj
395 newSysLocalDs ccall_adj_ty `thenDs` \ x_ccall_adj ->
397 mkLams [stbl_value] $
398 bindNonRec x_ccall_adj ccall_adj $
399 Note (Coerce (mkTyConApp ioTyCon [res_ty]) ccall_adj_ty)
402 newSysLocalDs (coreExprType ccall_io_adj) `thenDs` \ x_ccall_io_adj ->
403 let io_app = mkLams tvs $
405 stbl_app x_ccall_io_adj ccall_io_adj addrTy
407 returnDs (NonRec i io_app, fe, h_code, c_code)
410 (tvs,sans_foralls) = splitForAllTys ty
411 ([arg_ty], io_res) = splitFunTys sans_foralls
413 Just (ioTyCon, [res_ty]) = splitTyConApp_maybe io_res
415 export_ty = mkFunTy (mkTyConApp stablePtrTyCon [arg_ty]) arg_ty
417 toCName :: Id -> String
418 toCName i = showSDoc (pprCode CStyle (ppr (idName i)))
424 \subsection{Generating @foreign export@ stubs}
428 For each @foreign export@ function, a C stub function is generated.
429 The C stub constructs the application of the exported Haskell function
430 using the hugs/ghc rts invocation API.
433 fexportEntry :: FAST_STRING -> Id -> [Type] -> Maybe Type -> CallConv -> (SDoc, SDoc)
434 fexportEntry c_nm helper args res cc = (header_bits, c_bits)
436 -- name of the (Haskell) helper function generated by the desugarer.
437 h_nm = ppr helper <> text "_closure"
438 -- prototype for the exported function.
439 header_bits = ptext SLIT("extern") <+> fun_proto <> semi
441 fun_proto = cResType <+> pprCconv <+> ptext c_nm <>
442 parens (hsep (punctuate comma (zipWith (<+>) cParamTypes c_args)))
449 , text "SchedulerStatus rc;"
451 -- create the application + perform it.
452 , text "rc=rts_evalIO" <>
453 parens (foldl appArg (text "(StgClosure*)&" <> h_nm) (zip args c_args) <> comma <> text "&ret") <> semi
459 text "rts_apply" <> parens (acc <> comma <> mkHObj a <> parens c_a)
461 cParamTypes = map showStgType args
465 Nothing -> text "void"
466 Just t -> showStgType t
469 | cc == cCallConv = empty
470 | otherwise = pprCallConv cc
472 declareResult = text "HaskellObj ret;"
474 externDecl = mkExtern (text "HaskellObj") h_nm
476 mkExtern ty nm = text "extern" <+> ty <+> nm <> semi
479 text "rts_checkSchedStatus" <>
480 parens (doubleQuotes (ptext c_nm) <> comma <> text "rc") <> semi $$
482 Nothing -> text "return"
483 Just _ -> text "return" <> parens (res_name)) <> semi
488 Just t -> unpackHObj t <> parens (text "ret")
490 c_args = zipWith (\ _ n -> text ('a':show n)) args [0..]
492 mkHObj :: Type -> SDoc
493 mkHObj t = text "rts_mk" <> showFFIType t
495 unpackHObj :: Type -> SDoc
496 unpackHObj t = text "rts_get" <> showFFIType t
498 showStgType :: Type -> SDoc
499 showStgType t = text "Stg" <> showFFIType t
501 showFFIType :: Type -> SDoc
502 showFFIType t = text (getOccString (getName tc))
504 tc = case splitTyConApp_maybe t of
506 Nothing -> pprPanic "showFFIType" (ppr t)