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, mkWildId, mkUserId )
26 import Const ( Literal(..) )
27 import Module ( Module )
28 import Name ( mkGlobalName, nameModule, nameOccName, getOccString,
29 mkForeignExportOcc, isLocalName,
30 NamedThing(..), Provenance(..), ExportFlag(..)
32 import PrelVals ( realWorldPrimId )
33 import PrelInfo ( deRefStablePtr_NAME, bindIO_NAME, makeStablePtr_NAME )
34 import Type ( splitAlgTyConApp_maybe,
35 splitTyConApp_maybe, splitFunTys, splitForAllTys,
36 Type, mkFunTys, mkForAllTys, mkTyConApp,
37 mkTyVarTy, mkFunTy, splitAppTy
39 import PrimOp ( PrimOp(..) )
41 import TysPrim ( realWorldStatePrimTy, addrPrimTy )
42 import TysWiredIn ( unitTyCon, addrTy, stablePtrTyCon,
43 unboxedTupleCon, addrDataCon
49 Desugaring of @foreign@ declarations is naturally split up into
50 parts, an @import@ and an @export@ part. A @foreign import@
53 foreign import cc nm f :: prim_args -> IO prim_res
57 f :: prim_args -> IO prim_res
58 f a1 ... an = _ccall_ nm cc a1 ... an
60 so we reuse the desugaring code in @DsCCall@ to deal with these.
64 -> [TypecheckedForeignDecl]
65 -> DsM ( [CoreBind] -- desugared foreign imports
66 , [CoreBind] -- helper functions for foreign exports
67 , SDoc -- Header file prototypes for "foreign exported" functions.
68 , SDoc -- C stubs to use when calling "foreign exported" funs.
70 dsForeigns mod_name fos = foldlDs combine ([],[],empty,empty) fos
72 combine (acc_fi, acc_fe, acc_h, acc_c) fo@(ForeignDecl i imp_exp _ ext_nm cconv _)
73 | isForeignImport = -- foreign import (dynamic)?
74 dsFImport i (idType i) uns ext_nm cconv `thenDs` \ b ->
75 returnDs (b:acc_fi, acc_fe, acc_h, acc_c)
77 dsFLabel i ext_nm `thenDs` \ b ->
78 returnDs (b:acc_fi, acc_fe, acc_h, acc_c)
80 dsFExportDynamic i (idType i) mod_name ext_nm cconv `thenDs` \ (fi,fe,h,c) ->
81 returnDs (fi:acc_fi, fe:acc_fe, h $$ acc_h, c $$ acc_c)
83 | otherwise = -- foreign export
84 dsFExport i (idType i) mod_name ext_nm cconv False `thenDs` \ (fe,h,c) ->
85 returnDs (acc_fi, fe:acc_fe, h $$ acc_h, c $$ acc_c)
97 (FoImport uns) = imp_exp
101 Desugaring foreign imports is just the matter of creating a binding
102 that on its RHS unboxes its arguments, performs the external call
103 (using the CCallOp primop), before boxing the result up and returning it.
107 -> Type -- Type of foreign import.
108 -> Bool -- True <=> might cause Haskell GC
112 dsFImport nm ty may_not_gc ext_name cconv =
113 newSysLocalDs realWorldStatePrimTy `thenDs` \ old_s ->
114 splitForeignTyDs ty `thenDs` \ (tvs, args, mbIoDataCon, io_res_ty) ->
117 | is_io_action = old_s
118 | otherwise = realWorldPrimId
120 arg_exprs = map (Var) args
127 mapAndUnzipDs unboxArg arg_exprs `thenDs` \ (unboxed_args, arg_wrappers) ->
128 (if not is_io_action then
129 newSysLocalDs realWorldStatePrimTy `thenDs` \ state_tok ->
130 wrapUnboxedValue io_res_ty `thenDs` \ (ccall_result_ty, v, res_v) ->
131 returnDs ( ccall_result_ty
132 , \ prim_app -> Case prim_app (mkWildId ccall_result_ty)
133 [(DataCon (unboxedTupleCon 2), [state_tok, v], res_v)])
135 boxResult io_res_ty) `thenDs` \ (final_result_ty, res_wrapper) ->
137 Dynamic -> getUniqueDs `thenDs` \ u ->
139 ExtName fs _ -> returnDs (Left fs)) `thenDs` \ label ->
141 val_args = Var the_state_arg : unboxed_args
142 final_args = Type inst_ty : val_args
144 -- A CCallOp has type (forall a. a), so we must instantiate
145 -- it at the full type, including the state argument
146 inst_ty = mkFunTys (map coreExprType val_args) final_result_ty
148 the_ccall_op = CCallOp label False (not may_not_gc) cconv
150 the_prim_app = mkPrimApp the_ccall_op (final_args :: [CoreArg])
152 body = foldr ($) (res_wrapper the_prim_app) arg_wrappers
155 | not is_io_action = body
156 | otherwise = Lam old_s body
158 newSysLocalDs (coreExprType the_body) `thenDs` \ ds ->
164 mkApps (Var (dataConId ioDataCon))
165 [Type io_res_ty, Var ds]
167 fo_rhs = mkLams (tvs ++ args)
168 (Let (NonRec ds (the_body::CoreExpr)) io_app)
170 returnDs (NonRec nm fo_rhs)
173 Given the type of a foreign import declaration, split it up into
174 its constituent parts.
177 splitForeignTyDs :: Type -> DsM ([TyVar], [Id], Maybe DataCon, Type)
178 splitForeignTyDs ty =
179 newSysLocalsDs arg_tys `thenDs` \ ds_args ->
180 case splitAlgTyConApp_maybe res_ty of
181 Just (_,(io_res_ty:_),(ioCon:_)) -> -- .... -> IO t
182 returnDs (tvs, ds_args, Just ioCon, io_res_ty)
184 returnDs (tvs, ds_args, Nothing, res_ty)
186 (arg_tys, res_ty) = splitFunTys sans_foralls
187 (tvs, sans_foralls) = splitForAllTys ty
194 dsFLabel :: Id -> ExtName -> DsM CoreBind
195 dsFLabel nm ext_name = returnDs (NonRec nm fo_rhs)
197 fo_rhs = mkConApp addrDataCon [mkLit (MachLitLit enm addrPrimTy)]
201 Dynamic -> panic "dsFLabel: Dynamic - shouldn't ever happen."
205 The function that does most of the work for 'foreign export' declarations.
206 (see below for the boilerplate code a 'foreign export' declaration expands
209 For each 'foreign export foo' in a module M we generate:
211 * a C function 'foo', which calls
212 * a Haskell stub 'M.$ffoo', which calls
214 the user-written Haskell function 'M.foo'.
218 -> Type -- Type of foreign export.
222 -> Bool -- True => invoke IO action that's hanging off
223 -- the first argument's stable pointer
228 dsFExport i ty mod_name ext_name cconv isDyn =
229 getUniqueDs `thenDs` \ uniq ->
230 getSrcLocDs `thenDs` \ src_loc ->
232 f_helper_glob = mkUserId helper_name helper_ty
236 | isLocalName name = mod_name
237 | otherwise = nameModule name
239 occ = mkForeignExportOcc (nameOccName name)
240 prov = LocalDef src_loc Exported
241 helper_name = mkGlobalName uniq mod occ prov
243 newSysLocalsDs fe_arg_tys `thenDs` \ fe_args ->
245 newSysLocalDs stbl_ptr_ty `thenDs` \ stbl_ptr ->
246 newSysLocalDs stbl_ptr_to_ty `thenDs` \ stbl_value ->
247 dsLookupGlobalValue deRefStablePtr_NAME `thenDs` \ deRefStablePtrId ->
249 the_deref_app = mkApps (Var deRefStablePtrId)
250 [ Type stbl_ptr_to_ty, Var stbl_ptr ]
252 newSysLocalDs (coreExprType the_deref_app) `thenDs` \ x_deref_app ->
253 dsLookupGlobalValue bindIO_NAME `thenDs` \ bindIOId ->
254 newSysLocalDs (mkFunTy stbl_ptr_to_ty
255 (mkTyConApp ioTyCon [res_ty])) `thenDs` \ x_cont ->
258 bindNonRec x_cont (mkLams [stbl_value] cont) $
259 bindNonRec x_deref_app the_deref_app
260 (mkApps (Var bindIOId)
261 [ Type stbl_ptr_to_ty
266 returnDs (stbl_value, stbl_app, stbl_ptr)
270 panic "stbl_ptr" -- should never be touched.
271 )) `thenDs` \ (i, getFun_wrapper, stbl_ptr) ->
274 | isDyn = stbl_ptr:fe_args
275 | otherwise = fe_args
278 | isDyn = stbl_ptr_ty:helper_arg_tys
279 | otherwise = helper_arg_tys
283 mkApps (Var i) (map (Type . mkTyVarTy) tvs ++ map Var fe_args)
285 getModuleAndGroupDs `thenDs` \ (mod,_) ->
286 getUniqueDs `thenDs` \ uniq ->
288 the_body = mkLams (tvs ++ wrapper_args) the_app
293 Dynamic -> panic "dsFExport: Dynamic - shouldn't ever happen."
295 (h_stub, c_stub) = fexportEntry c_nm f_helper_glob wrapper_arg_tys the_result_ty cconv isDyn
297 returnDs (NonRec f_helper_glob the_body, h_stub, c_stub)
301 (tvs,sans_foralls) = splitForAllTys ty
302 (fe_arg_tys', io_res) = splitFunTys sans_foralls
305 Just (ioTyCon, [res_ty]) = splitTyConApp_maybe io_res
307 (_, stbl_ptr_ty') = splitForAllTys stbl_ptr_ty
308 (_, stbl_ptr_to_ty) = splitAppTy stbl_ptr_ty'
311 | isDyn = tail fe_arg_tys'
312 | otherwise = fe_arg_tys'
314 (stbl_ptr_ty, helper_arg_tys) =
316 (x:xs) | isDyn -> (x,xs)
317 ls -> (error "stbl_ptr_ty", ls)
321 mkFunTys arg_tys io_res
324 | isDyn = stbl_ptr_ty : helper_arg_tys
325 | otherwise = helper_arg_tys
328 case splitTyConApp_maybe io_res of
330 case splitTyConApp_maybe res_ty of
331 Just (tc,_) | getUnique tc /= getUnique unitTyCon -> Just res_ty
337 "foreign export dynamic" lets you dress up Haskell IO actions
338 of some fixed type behind an externally callable interface (i.e.,
339 as a C function pointer). Useful for callbacks and stuff.
342 foreign export stdcall f :: (Addr -> Int -> IO Int) -> IO Addr
344 -- Haskell-visible constructor, which is generated from the
347 f :: (Addr -> Int -> IO Int) -> IO Addr
348 f cback = IO ( \ s1# ->
349 case makeStablePtr# cback s1# of { StateAndStablePtr# s2# sp# ->
350 case _ccall_ "mkAdjustor" sp# ``f_helper'' s2# of
351 StateAndAddr# s3# a# ->
361 foreign export "f_helper" f_helper :: StablePtr (Addr -> Int -> IO Int) -> Addr -> Int -> IO Int
362 -- `special' foreign export that invokes the closure pointed to by the
367 dsFExportDynamic :: Id
368 -> Type -- Type of foreign export.
372 -> DsM (CoreBind, CoreBind, SDoc, SDoc)
373 dsFExportDynamic i ty mod_name ext_name cconv =
374 newSysLocalDs ty `thenDs` \ fe_id ->
376 -- hack: need to get at the name of the C stub we're about to generate.
377 fe_nm = toCName fe_id
378 fe_ext_name = ExtName (_PK_ fe_nm) Nothing
380 dsFExport i export_ty mod_name fe_ext_name cconv True `thenDs` \ (fe@(NonRec fe_helper fe_expr), h_code, c_code) ->
381 newSysLocalDs arg_ty `thenDs` \ cback ->
382 dsLookupGlobalValue makeStablePtr_NAME `thenDs` \ makeStablePtrId ->
384 mk_stbl_ptr_app = mkApps (Var makeStablePtrId) [ Type arg_ty, Var cback ]
385 mk_stbl_ptr_app_ty = coreExprType mk_stbl_ptr_app
387 newSysLocalDs mk_stbl_ptr_app_ty `thenDs` \ x_mk_stbl_ptr_app ->
388 dsLookupGlobalValue bindIO_NAME `thenDs` \ bindIOId ->
389 newSysLocalDs (mkTyConApp stablePtrTyCon [arg_ty]) `thenDs` \ stbl_value ->
391 stbl_app = \ x_cont cont ret_ty ->
392 bindNonRec x_cont cont $
393 bindNonRec x_mk_stbl_ptr_app mk_stbl_ptr_app $
394 (mkApps (Var bindIOId)
395 [ Type (mkTyConApp stablePtrTyCon [arg_ty])
397 , Var x_mk_stbl_ptr_app
402 The arguments to the external function which will
403 create a little bit of (template) code on the fly
404 for allowing the (stable pointed) Haskell closure
405 to be entered using an external calling convention
408 adj_args = [ mkLit (mkMachInt (fromInt (callConvToInt cconv)))
410 , mkLit (MachLitLit (_PK_ fe_nm) addrPrimTy)
412 -- name of external entry point providing these services.
413 -- (probably in the RTS.)
414 adjustor = SLIT("createAdjustor")
416 dsCCall adjustor adj_args False False addrTy `thenDs` \ ccall_adj ->
417 let ccall_adj_ty = coreExprType ccall_adj
419 newSysLocalDs ccall_adj_ty `thenDs` \ x_ccall_adj ->
421 mkLams [stbl_value] $
422 bindNonRec x_ccall_adj ccall_adj $
423 Note (Coerce (mkTyConApp ioTyCon [res_ty]) ccall_adj_ty)
426 newSysLocalDs (coreExprType ccall_io_adj) `thenDs` \ x_ccall_io_adj ->
427 let io_app = mkLams tvs $
429 stbl_app x_ccall_io_adj ccall_io_adj addrTy
431 returnDs (NonRec i io_app, fe, h_code, c_code)
434 (tvs,sans_foralls) = splitForAllTys ty
435 ([arg_ty], io_res) = splitFunTys sans_foralls
437 Just (ioTyCon, [res_ty]) = splitTyConApp_maybe io_res
439 export_ty = mkFunTy (mkTyConApp stablePtrTyCon [arg_ty]) arg_ty
441 toCName :: Id -> String
442 toCName i = showSDoc (pprCode CStyle (ppr (idName i)))
448 \subsection{Generating @foreign export@ stubs}
452 For each @foreign export@ function, a C stub function is generated.
453 The C stub constructs the application of the exported Haskell function
454 using the hugs/ghc rts invocation API.
457 fexportEntry :: FAST_STRING
464 fexportEntry c_nm helper args res cc isDyn = (header_bits, c_bits)
466 -- name of the (Haskell) helper function generated by the desugarer.
467 h_nm = ppr helper <> text "_closure"
468 -- prototype for the exported function.
469 header_bits = ptext SLIT("extern") <+> fun_proto <> semi
471 fun_proto = cResType <+> pprCconv <+> ptext c_nm <>
472 parens (hsep (punctuate comma (zipWith (<+>) cParamTypes proto_args)))
479 , text "SchedulerStatus rc;"
481 -- create the application + perform it.
482 , text "rc=rts_evalIO" <>
483 parens (foldl appArg (text "(StgClosure*)&" <> h_nm) (zip args c_args) <> comma <> text "&ret") <> semi
489 text "rts_apply" <> parens (acc <> comma <> mkHObj a <> parens c_a)
491 cParamTypes = map showStgType real_args
495 Nothing -> text "void"
496 Just t -> showStgType t
499 | cc == cCallConv = empty
500 | otherwise = pprCallConv cc
502 declareResult = text "HaskellObj ret;"
504 externDecl = mkExtern (text "HaskellObj") h_nm
506 mkExtern ty nm = text "extern" <+> ty <+> nm <> semi
509 text "rts_checkSchedStatus" <>
510 parens (doubleQuotes (ptext c_nm) <> comma <> text "rc") <> semi $$
512 Nothing -> text "return"
513 Just _ -> text "return" <> parens (res_name)) <> semi
518 Just t -> unpackHObj t <> parens (text "ret")
520 c_args = mkCArgNames 0 args
523 If we're generating an entry point for a 'foreign export ccall dynamic',
524 then we receive the return address of the C function that wants to
525 invoke a Haskell function as any other C function, as second arg.
526 This arg is unused within the body of the generated C stub, but
527 needed by the Adjustor.c code to get the stack cleanup right.
529 (proto_args, real_args)
530 | cc == cCallConv && isDyn = ( text "a0" : text "a_" : mkCArgNames 1 (tail args)
531 , head args : addrTy : tail args)
532 | otherwise = (mkCArgNames 0 args, args)
534 mkCArgNames :: Int -> [a] -> [SDoc]
535 mkCArgNames n as = zipWith (\ _ n -> text ('a':show n)) as [n..]
537 mkHObj :: Type -> SDoc
538 mkHObj t = text "rts_mk" <> text (showFFIType t)
540 unpackHObj :: Type -> SDoc
541 unpackHObj t = text "rts_get" <> text (showFFIType t)
543 showStgType :: Type -> SDoc
544 showStgType t = text "Stg" <> text (showFFIType t)
546 showFFIType :: Type -> String
547 showFFIType t = getOccString (getName tc)
549 tc = case splitTyConApp_maybe t of
551 Nothing -> pprPanic "showFFIType" (ppr t)