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, mkVanillaId )
26 import Const ( Literal(..) )
27 import Module ( Module, moduleUserString )
28 import Name ( mkGlobalName, nameModule, nameOccName, getOccString,
29 mkForeignExportOcc, isLocalName,
30 NamedThing(..), Provenance(..), ExportFlag(..)
32 import PrelInfo ( deRefStablePtr_NAME, bindIO_NAME, makeStablePtr_NAME, realWorldPrimId )
33 import Type ( splitAlgTyConApp_maybe, unUsgTy,
34 splitTyConApp_maybe, splitFunTys, splitForAllTys,
35 Type, mkFunTys, mkForAllTys, mkTyConApp,
36 mkTyVarTy, mkFunTy, splitAppTy
38 import PrimOp ( PrimOp(..) )
40 import TysPrim ( realWorldStatePrimTy, addrPrimTy )
41 import TysWiredIn ( unitTyCon, addrTy, stablePtrTyCon,
42 unboxedTupleCon, addrDataCon
47 #if __GLASGOW_HASKELL__ >= 404
48 import GlaExts ( fromInt )
52 Desugaring of @foreign@ declarations is naturally split up into
53 parts, an @import@ and an @export@ part. A @foreign import@
56 foreign import cc nm f :: prim_args -> IO prim_res
60 f :: prim_args -> IO prim_res
61 f a1 ... an = _ccall_ nm cc a1 ... an
63 so we reuse the desugaring code in @DsCCall@ to deal with these.
67 -> [TypecheckedForeignDecl]
68 -> DsM ( [CoreBind] -- desugared foreign imports
69 , [CoreBind] -- helper functions for foreign exports
70 , SDoc -- Header file prototypes for
71 -- "foreign exported" functions.
72 , SDoc -- C stubs to use when calling
73 -- "foreign exported" functions.
75 dsForeigns mod_name fos = foldlDs combine ([],[],empty,empty) fos
77 combine (acc_fi, acc_fe, acc_h, acc_c) fo@(ForeignDecl i imp_exp _ ext_nm cconv _)
78 | isForeignImport = -- foreign import (dynamic)?
79 dsFImport i (idType i) uns ext_nm cconv `thenDs` \ b ->
80 returnDs (b:acc_fi, acc_fe, acc_h, acc_c)
82 dsFLabel i ext_nm `thenDs` \ b ->
83 returnDs (b:acc_fi, acc_fe, acc_h, acc_c)
85 dsFExportDynamic i (idType i) mod_name ext_nm cconv `thenDs` \ (fi,fe,h,c) ->
86 returnDs (fi:acc_fi, fe:acc_fe, h $$ acc_h, c $$ acc_c)
88 | otherwise = -- foreign export
89 dsFExport i (idType i) mod_name ext_nm cconv False `thenDs` \ (fe,h,c) ->
90 returnDs (acc_fi, fe:acc_fe, h $$ acc_h, c $$ acc_c)
102 (FoImport uns) = imp_exp
106 Desugaring foreign imports is just the matter of creating a binding
107 that on its RHS unboxes its arguments, performs the external call
108 (using the @CCallOp@ primop), before boxing the result up and returning it.
112 -> Type -- Type of foreign import.
113 -> Bool -- True <=> might cause Haskell GC
117 dsFImport nm ty may_not_gc ext_name cconv =
118 newSysLocalDs realWorldStatePrimTy `thenDs` \ old_s ->
119 splitForeignTyDs ty `thenDs` \ (tvs, args, mbIoDataCon, io_res_ty) ->
122 | is_io_action = old_s
123 | otherwise = realWorldPrimId
125 arg_exprs = map (Var) args
132 mapAndUnzipDs unboxArg arg_exprs `thenDs` \ (unboxed_args, arg_wrappers) ->
133 (if not is_io_action then
134 newSysLocalDs realWorldStatePrimTy `thenDs` \ state_tok ->
135 wrapUnboxedValue io_res_ty `thenDs` \ (ccall_result_ty, v, res_v) ->
136 returnDs ( ccall_result_ty
137 , \ prim_app -> Case prim_app (mkWildId ccall_result_ty)
138 [(DataCon (unboxedTupleCon 2), [state_tok, v], res_v)])
140 boxResult io_res_ty) `thenDs` \ (final_result_ty, res_wrapper) ->
142 Dynamic -> getUniqueDs `thenDs` \ u ->
144 ExtName fs _ -> returnDs (Left fs)) `thenDs` \ lbl ->
146 val_args = Var the_state_arg : unboxed_args
147 final_args = Type inst_ty : val_args
149 -- A CCallOp has type (forall a. a), so we must instantiate
150 -- it at the full type, including the state argument
151 inst_ty = mkFunTys (map coreExprType val_args) final_result_ty
153 the_ccall_op = CCallOp lbl False (not may_not_gc) cconv
155 the_prim_app = mkPrimApp the_ccall_op (final_args :: [CoreArg])
157 body = foldr ($) (res_wrapper the_prim_app) arg_wrappers
160 | not is_io_action = body
161 | otherwise = Lam old_s body
163 newSysLocalDs (coreExprType the_body) `thenDs` \ ds ->
169 mkApps (Var (dataConId ioDataCon))
170 [Type io_res_ty, Var ds]
172 fo_rhs = mkLams (tvs ++ args)
173 (mkDsLet (NonRec ds (the_body::CoreExpr)) io_app)
175 returnDs (NonRec nm fo_rhs)
178 Given the type of a foreign import declaration, split it up into
179 its constituent parts.
182 splitForeignTyDs :: Type -> DsM ([TyVar], [Id], Maybe DataCon, Type)
183 splitForeignTyDs ty =
184 newSysLocalsDs arg_tys `thenDs` \ ds_args ->
185 case splitAlgTyConApp_maybe res_ty of
186 Just (_,(io_res_ty:_),(ioCon:_)) -> -- .... -> IO t
187 returnDs (tvs, ds_args, Just ioCon, io_res_ty)
189 returnDs (tvs, ds_args, Nothing, res_ty)
191 (arg_tys, res_ty) = splitFunTys sans_foralls
192 (tvs, sans_foralls) = splitForAllTys ty
199 dsFLabel :: Id -> ExtName -> DsM CoreBind
200 dsFLabel nm ext_name = returnDs (NonRec nm fo_rhs)
202 fo_rhs = mkConApp addrDataCon [mkLit (MachLitLit enm addrPrimTy)]
206 Dynamic -> panic "dsFLabel: Dynamic - shouldn't ever happen."
210 The function that does most of the work for `@foreign export@' declarations.
211 (see below for the boilerplate code a `@foreign export@' declaration expands
214 For each `@foreign export foo@' in a module M we generate:
216 \item a C function `@foo@', which calls
217 \item a Haskell stub `@M.$ffoo@', which calls
219 the user-written Haskell function `@M.foo@'.
223 -> Type -- Type of foreign export.
227 -> Bool -- True => invoke IO action that's hanging off
228 -- the first argument's stable pointer
233 dsFExport i ty mod_name ext_name cconv isDyn =
234 getUniqueDs `thenDs` \ uniq ->
235 getSrcLocDs `thenDs` \ src_loc ->
237 f_helper_glob = mkVanillaId helper_name helper_ty
241 | isLocalName name = mod_name
242 | otherwise = nameModule name
244 occ = mkForeignExportOcc (nameOccName name)
245 prov = LocalDef src_loc Exported
246 helper_name = mkGlobalName uniq mod occ prov
248 newSysLocalsDs fe_arg_tys `thenDs` \ fe_args ->
250 newSysLocalDs stbl_ptr_ty `thenDs` \ stbl_ptr ->
251 newSysLocalDs stbl_ptr_to_ty `thenDs` \ stbl_value ->
252 dsLookupGlobalValue deRefStablePtr_NAME `thenDs` \ deRefStablePtrId ->
254 the_deref_app = mkApps (Var deRefStablePtrId)
255 [ Type stbl_ptr_to_ty, Var stbl_ptr ]
257 newSysLocalDs (coreExprType the_deref_app) `thenDs` \ x_deref_app ->
258 dsLookupGlobalValue bindIO_NAME `thenDs` \ bindIOId ->
259 newSysLocalDs (mkFunTy stbl_ptr_to_ty
260 (mkTyConApp ioTyCon [res_ty])) `thenDs` \ x_cont ->
263 bindNonRec x_cont (mkLams [stbl_value] cont) $
264 bindNonRec x_deref_app the_deref_app
265 (mkApps (Var bindIOId)
266 [ Type stbl_ptr_to_ty
271 returnDs (stbl_value, stbl_app, stbl_ptr)
275 panic "stbl_ptr" -- should never be touched.
276 )) `thenDs` \ (i, getFun_wrapper, stbl_ptr) ->
279 | isDyn = stbl_ptr:fe_args
280 | otherwise = fe_args
283 | isDyn = stbl_ptr_ty:helper_arg_tys
284 | otherwise = helper_arg_tys
288 mkApps (Var i) (map (Type . mkTyVarTy) tvs ++ map Var fe_args)
290 getModuleDs `thenDs` \ mod ->
291 getUniqueDs `thenDs` \ uniq ->
293 the_body = mkLams (tvs ++ wrapper_args) the_app
298 Dynamic -> panic "dsFExport: Dynamic - shouldn't ever happen."
300 (h_stub, c_stub) = fexportEntry (moduleUserString mod)
302 wrapper_arg_tys the_result_ty cconv isDyn
304 returnDs (NonRec f_helper_glob the_body, h_stub, c_stub)
308 (tvs,sans_foralls) = splitForAllTys ty
309 (fe_arg_tys', io_res) = splitFunTys sans_foralls
312 Just (ioTyCon, [res_ty]) = splitTyConApp_maybe io_res
314 (_, stbl_ptr_ty') = splitForAllTys stbl_ptr_ty
315 (_, stbl_ptr_to_ty) = splitAppTy stbl_ptr_ty'
318 | isDyn = tail fe_arg_tys'
319 | otherwise = fe_arg_tys'
321 (stbl_ptr_ty, helper_arg_tys) =
323 (x:xs) | isDyn -> (x,xs)
324 ls -> (error "stbl_ptr_ty", ls)
328 mkFunTys arg_tys io_res
331 | isDyn = stbl_ptr_ty : helper_arg_tys
332 | otherwise = helper_arg_tys
335 case splitTyConApp_maybe io_res of
337 case splitTyConApp_maybe res_ty of
338 Just (tc,_) | getUnique tc /= getUnique unitTyCon -> Just res_ty
344 @foreign export dynamic@ lets you dress up Haskell IO actions
345 of some fixed type behind an externally callable interface (i.e.,
346 as a C function pointer). Useful for callbacks and stuff.
349 foreign export stdcall f :: (Addr -> Int -> IO Int) -> IO Addr
351 -- Haskell-visible constructor, which is generated from the
354 f :: (Addr -> Int -> IO Int) -> IO Addr
355 f cback = IO ( \ s1# ->
356 case makeStablePtr# cback s1# of { StateAndStablePtr# s2# sp# ->
357 case _ccall_ "mkAdjustor" sp# ``f_helper'' s2# of
358 StateAndAddr# s3# a# ->
368 foreign export "f_helper" f_helper :: StablePtr (Addr -> Int -> IO Int) -> Addr -> Int -> IO Int
369 -- `special' foreign export that invokes the closure pointed to by the
374 dsFExportDynamic :: Id
375 -> Type -- Type of foreign export.
379 -> DsM (CoreBind, CoreBind, SDoc, SDoc)
380 dsFExportDynamic i ty mod_name ext_name cconv =
381 newSysLocalDs ty `thenDs` \ fe_id ->
383 -- hack: need to get at the name of the C stub we're about to generate.
384 fe_nm = toCName fe_id
385 fe_ext_name = ExtName (_PK_ fe_nm) Nothing
387 dsFExport i export_ty mod_name fe_ext_name cconv True
388 `thenDs` \ (fe@(NonRec fe_helper fe_expr), h_code, c_code) ->
389 newSysLocalDs arg_ty `thenDs` \ cback ->
390 dsLookupGlobalValue makeStablePtr_NAME `thenDs` \ makeStablePtrId ->
392 mk_stbl_ptr_app = mkApps (Var makeStablePtrId) [ Type arg_ty, Var cback ]
393 mk_stbl_ptr_app_ty = coreExprType mk_stbl_ptr_app
395 newSysLocalDs mk_stbl_ptr_app_ty `thenDs` \ x_mk_stbl_ptr_app ->
396 dsLookupGlobalValue bindIO_NAME `thenDs` \ bindIOId ->
397 newSysLocalDs (mkTyConApp stablePtrTyCon [arg_ty]) `thenDs` \ stbl_value ->
399 stbl_app = \ x_cont cont ret_ty ->
400 bindNonRec x_cont cont $
401 bindNonRec x_mk_stbl_ptr_app mk_stbl_ptr_app $
402 (mkApps (Var bindIOId)
403 [ Type (mkTyConApp stablePtrTyCon [arg_ty])
405 , Var x_mk_stbl_ptr_app
410 The arguments to the external function which will
411 create a little bit of (template) code on the fly
412 for allowing the (stable pointed) Haskell closure
413 to be entered using an external calling convention
416 adj_args = [ mkLit (mkMachInt (fromInt (callConvToInt cconv)))
418 , mkLit (MachLitLit (_PK_ fe_nm) addrPrimTy)
420 -- name of external entry point providing these services.
421 -- (probably in the RTS.)
422 adjustor = SLIT("createAdjustor")
424 dsCCall adjustor adj_args False False addrTy `thenDs` \ ccall_adj ->
425 let ccall_adj_ty = coreExprType ccall_adj
427 newSysLocalDs ccall_adj_ty `thenDs` \ x_ccall_adj ->
429 mkLams [stbl_value] $
430 bindNonRec x_ccall_adj ccall_adj $
431 Note (Coerce (mkTyConApp ioTyCon [res_ty]) (unUsgTy ccall_adj_ty))
434 newSysLocalDs (coreExprType ccall_io_adj) `thenDs` \ x_ccall_io_adj ->
435 let io_app = mkLams tvs $
437 stbl_app x_ccall_io_adj ccall_io_adj addrTy
439 returnDs (NonRec i io_app, fe, h_code, c_code)
442 (tvs,sans_foralls) = splitForAllTys ty
443 ([arg_ty], io_res) = splitFunTys sans_foralls
445 Just (ioTyCon, [res_ty]) = splitTyConApp_maybe io_res
447 export_ty = mkFunTy (mkTyConApp stablePtrTyCon [arg_ty]) arg_ty
449 toCName :: Id -> String
450 toCName i = showSDoc (pprCode CStyle (ppr (idName i)))
456 \subsection{Generating @foreign export@ stubs}
460 For each @foreign export@ function, a C stub function is generated.
461 The C stub constructs the application of the exported Haskell function
462 using the hugs/ghc rts invocation API.
465 fexportEntry :: String
473 fexportEntry mod_nm c_nm helper args res cc isDyn = (header_bits, c_bits)
475 -- name of the (Haskell) helper function generated by the desugarer.
476 h_nm = ppr helper <> text "_closure"
477 -- prototype for the exported function.
478 header_bits = ptext SLIT("extern") <+> fun_proto <> semi
480 fun_proto = cResType <+> pprCconv <+> ptext c_nm <>
481 parens (hsep (punctuate comma (zipWith (<+>) cParamTypes proto_args)))
488 , text "SchedulerStatus rc;"
490 -- create the application + perform it.
491 , text "rc=rts_evalIO" <>
492 parens (foldl appArg (text "(StgClosure*)&" <> h_nm) (zip args c_args) <> comma <> text "&ret") <> semi
498 text "rts_apply" <> parens (acc <> comma <> mkHObj a <> parens c_a)
500 cParamTypes = map showStgType real_args
504 Nothing -> text "void"
505 Just t -> showStgType t
508 | cc == cCallConv = empty
509 | otherwise = pprCallConv cc
511 declareResult = text "HaskellObj ret;"
513 externDecl = mkExtern (text "HaskellObj") h_nm
515 mkExtern ty nm = text "extern" <+> ty <+> nm <> semi
518 text "rts_checkSchedStatus" <>
519 parens (doubleQuotes (text mod_nm <> char '.' <> ptext c_nm) <> comma <> text "rc") <> semi $$
521 Nothing -> text "return"
522 Just _ -> text "return" <> parens (res_name)) <> semi
527 Just t -> unpackHObj t <> parens (text "ret")
529 c_args = mkCArgNames 0 args
532 If we're generating an entry point for a 'foreign export ccall dynamic',
533 then we receive the return address of the C function that wants to
534 invoke a Haskell function as any other C function, as second arg.
535 This arg is unused within the body of the generated C stub, but
536 needed by the Adjustor.c code to get the stack cleanup right.
538 (proto_args, real_args)
539 | cc == cCallConv && isDyn = ( text "a0" : text "a_" : mkCArgNames 1 (tail args)
540 , head args : addrTy : tail args)
541 | otherwise = (mkCArgNames 0 args, args)
543 mkCArgNames :: Int -> [a] -> [SDoc]
544 mkCArgNames n as = zipWith (\ _ n -> text ('a':show n)) as [n..]
546 mkHObj :: Type -> SDoc
547 mkHObj t = text "rts_mk" <> text (showFFIType t)
549 unpackHObj :: Type -> SDoc
550 unpackHObj t = text "rts_get" <> text (showFFIType t)
552 showStgType :: Type -> SDoc
553 showStgType t = text "Stg" <> text (showFFIType t)
555 showFFIType :: Type -> String
556 showFFIType t = getOccString (getName tc)
558 tc = case splitTyConApp_maybe t of
560 Nothing -> pprPanic "showFFIType" (ppr t)