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, mkFCall, boxResult, unboxArg, resultWrapper )
18 import HsSyn ( ForeignDecl(..), ForeignExport(..),
19 ForeignImport(..), CImportSpec(..) )
20 import TcHsSyn ( TypecheckedForeignDecl )
21 import CoreUtils ( exprType, mkInlineMe )
22 import Id ( Id, idType, idName, mkSysLocal, setInlinePragma )
23 import Literal ( Literal(..) )
24 import Module ( Module, moduleUserString )
25 import Name ( getOccString, NamedThing(..) )
26 import OccName ( encodeFS )
27 import Type ( repType, eqType )
28 import TcType ( Type, mkFunTys, mkForAllTys, mkTyConApp,
29 mkFunTy, tcSplitTyConApp_maybe,
30 tcSplitForAllTys, tcSplitFunTys, tcTyConAppArgs,
33 import ForeignCall ( ForeignCall(..), CCallSpec(..),
36 CCallConv(..), ccallConvToInt,
39 import CStrings ( CLabelString )
40 import TysWiredIn ( unitTy, stablePtrTyCon )
41 import TysPrim ( addrPrimTy )
42 import PrelNames ( hasKey, ioTyConKey, newStablePtrName, bindIOName )
43 import BasicTypes ( Activation( NeverActive ) )
44 import ErrUtils ( addShortWarnLocLine )
46 import Maybe ( fromJust )
50 Desugaring of @foreign@ declarations is naturally split up into
51 parts, an @import@ and an @export@ part. A @foreign import@
54 foreign import cc nm f :: prim_args -> IO prim_res
58 f :: prim_args -> IO prim_res
59 f a1 ... an = _ccall_ nm cc a1 ... an
61 so we reuse the desugaring code in @DsCCall@ to deal with these.
64 type Binding = (Id, CoreExpr) -- No rec/nonrec structure;
65 -- the occurrence analyser will sort it all out
68 -> [TypecheckedForeignDecl]
69 -> DsM ( [Id] -- Foreign-exported binders;
70 -- we have to generate code to register these
72 , SDoc -- Header file prototypes for
73 -- "foreign exported" functions.
74 , SDoc -- C stubs to use when calling
75 -- "foreign exported" functions.
76 , [FastString] -- headers that need to be included
77 -- into C code generated for this module
79 dsForeigns mod_name fos
80 = foldlDs combine ([], [], empty, empty, []) fos
82 combine (acc_feb, acc_f, acc_h, acc_c, acc_header)
83 (ForeignImport id _ spec depr loc)
84 = dsFImport mod_name id spec `thenDs` \(bs, h, c, hd) ->
85 warnDepr depr loc `thenDs` \_ ->
86 returnDs (acc_feb, bs ++ acc_f, h $$ acc_h, c $$ acc_c, hd ++ acc_header)
88 combine (acc_feb, acc_f, acc_h, acc_c, acc_header)
89 (ForeignExport id _ (CExport (CExportStatic ext_nm cconv)) depr loc)
90 = dsFExport mod_name id (idType id)
91 ext_nm cconv False `thenDs` \(h, c) ->
92 warnDepr depr loc `thenDs` \_ ->
93 returnDs (acc_feb, acc_f, h $$ acc_h, c $$ acc_c, acc_header)
95 warnDepr False _ = returnDs ()
96 warnDepr True loc = dsWarn (addShortWarnLocLine loc msg)
98 msg = ptext SLIT("foreign declaration uses deprecated non-standard syntax")
102 %************************************************************************
104 \subsection{Foreign import}
106 %************************************************************************
108 Desugaring foreign imports is just the matter of creating a binding
109 that on its RHS unboxes its arguments, performs the external call
110 (using the @CCallOp@ primop), before boxing the result up and returning it.
112 However, we create a worker/wrapper pair, thus:
114 foreign import f :: Int -> IO Int
116 f x = IO ( \s -> case x of { I# x# ->
117 case fw s x# of { (# s1, y# #) ->
120 fw s x# = ccall f s x#
122 The strictness/CPR analyser won't do this automatically because it doesn't look
123 inside returned tuples; but inlining this wrapper is a Really Good Idea
124 because it exposes the boxing to the call site.
130 -> DsM ([Binding], SDoc, SDoc, [FastString])
131 dsFImport modName id (CImport cconv safety header lib spec)
132 = dsCImport modName id spec cconv safety `thenDs` \(ids, h, c) ->
133 returnDs (ids, h, c, if nullFastString header then [] else [header])
134 -- FIXME: the `lib' field is needed for .NET ILX generation when invoking
135 -- routines that are external to the .NET runtime, but GHC doesn't
136 -- support such calls yet; if `nullFastString lib', the value was not given
137 dsFImport modName id (DNImport spec)
138 = dsFCall modName id (DNCall spec) `thenDs` \(ids, h, c) ->
139 returnDs (ids, h, c, [])
146 -> DsM ([Binding], SDoc, SDoc)
147 dsCImport modName id (CLabel cid) _ _
148 = ASSERT(fromJust resTy `eqType` addrPrimTy) -- typechecker ensures this
149 returnDs ([(id, rhs)], empty, empty)
151 (resTy, foRhs) = resultWrapper (idType id)
152 rhs = foRhs (mkLit (MachLabel cid))
153 dsCImport modName id (CFunction target) cconv safety
154 = dsFCall modName id (CCall (CCallSpec target cconv safety))
155 dsCImport modName id CWrapper cconv _
156 = dsFExportDynamic modName id cconv
160 %************************************************************************
162 \subsection{Foreign calls}
164 %************************************************************************
167 dsFCall mod_Name fn_id fcall
170 (tvs, fun_ty) = tcSplitForAllTys ty
171 (arg_tys, io_res_ty) = tcSplitFunTys fun_ty
172 -- Must use tcSplit* functions because we want to
173 -- see that (IO t) in the corner
175 newSysLocalsDs arg_tys `thenDs` \ args ->
176 mapAndUnzipDs unboxArg (map Var args) `thenDs` \ (val_args, arg_wrappers) ->
179 work_arg_ids = [v | Var v <- val_args] -- All guaranteed to be vars
181 -- These are the ids we pass to boxResult, which are used to decide
182 -- whether to touch# an argument after the call (used to keep
183 -- ForeignObj#s live across a 'safe' foreign import).
184 maybe_arg_ids | unsafe_call fcall = work_arg_ids
187 boxResult maybe_arg_ids io_res_ty `thenDs` \ (ccall_result_ty, res_wrapper) ->
189 getUniqueDs `thenDs` \ ccall_uniq ->
190 getUniqueDs `thenDs` \ work_uniq ->
193 worker_ty = mkForAllTys tvs (mkFunTys (map idType work_arg_ids) ccall_result_ty)
194 the_ccall_app = mkFCall ccall_uniq fcall val_args ccall_result_ty
195 work_rhs = mkLams tvs (mkLams work_arg_ids the_ccall_app)
196 work_id = mkSysLocal (encodeFS FSLIT("$wccall")) work_uniq worker_ty
199 work_app = mkApps (mkVarApps (Var work_id) tvs) val_args
200 wrapper_body = foldr ($) (res_wrapper work_app) arg_wrappers
201 wrap_rhs = mkInlineMe (mkLams (tvs ++ args) wrapper_body)
203 returnDs ([(work_id, work_rhs), (fn_id, wrap_rhs)], empty, empty)
205 unsafe_call (CCall (CCallSpec _ _ safety)) = playSafe safety
206 unsafe_call (DNCall _) = False
210 %************************************************************************
212 \subsection{Foreign export}
214 %************************************************************************
216 The function that does most of the work for `@foreign export@' declarations.
217 (see below for the boilerplate code a `@foreign export@' declaration expands
220 For each `@foreign export foo@' in a module M we generate:
222 \item a C function `@foo@', which calls
223 \item a Haskell stub `@M.$ffoo@', which calls
225 the user-written Haskell function `@M.foo@'.
229 -> Id -- Either the exported Id,
230 -- or the foreign-export-dynamic constructor
231 -> Type -- The type of the thing callable from C
232 -> CLabelString -- The name to export to C land
234 -> Bool -- True => foreign export dynamic
235 -- so invoke IO action that's hanging off
236 -- the first argument's stable pointer
237 -> DsM ( SDoc -- contents of Module_stub.h
238 , SDoc -- contents of Module_stub.c
241 dsFExport mod_name fn_id ty ext_name cconv isDyn
244 (tvs,sans_foralls) = tcSplitForAllTys ty
245 (fe_arg_tys', orig_res_ty) = tcSplitFunTys sans_foralls
246 -- We must use tcSplits here, because we want to see
247 -- the (IO t) in the corner of the type!
248 fe_arg_tys | isDyn = tail fe_arg_tys'
249 | otherwise = fe_arg_tys'
251 -- Look at the result type of the exported function, orig_res_ty
252 -- If it's IO t, return (t, True)
253 -- If it's plain t, return (t, False)
254 (case tcSplitTyConApp_maybe orig_res_ty of
255 -- We must use tcSplit here so that we see the (IO t) in
256 -- the type. [IO t is transparent to plain splitTyConApp.]
258 Just (ioTyCon, [res_ty])
259 -> ASSERT( ioTyCon `hasKey` ioTyConKey )
260 -- The function already returns IO t
261 returnDs (res_ty, True)
263 other -> -- The function returns t
264 returnDs (orig_res_ty, False)
266 `thenDs` \ (res_ty, -- t
267 is_IO_res_ty) -> -- Bool
272 = mkFExportCBits (moduleUserString mod) ext_name
273 (if isDyn then Nothing else Just fn_id)
274 fe_arg_tys res_ty is_IO_res_ty cconv
276 returnDs (h_stub, c_stub)
279 @foreign export dynamic@ lets you dress up Haskell IO actions
280 of some fixed type behind an externally callable interface (i.e.,
281 as a C function pointer). Useful for callbacks and stuff.
284 foreign export dynamic f :: (Addr -> Int -> IO Int) -> IO Addr
286 -- Haskell-visible constructor, which is generated from the above:
287 -- SUP: No check for NULL from createAdjustor anymore???
289 f :: (Addr -> Int -> IO Int) -> IO Addr
291 bindIO (newStablePtr cback)
292 (\StablePtr sp# -> IO (\s1# ->
293 case _ccall_ createAdjustor cconv sp# ``f_helper'' s1# of
294 (# s2#, a# #) -> (# s2#, A# a# #)))
296 foreign export "f_helper" f_helper :: StablePtr (Addr -> Int -> IO Int) -> Addr -> Int -> IO Int
297 -- `special' foreign export that invokes the closure pointed to by the
302 dsFExportDynamic :: Module
305 -> DsM ([Binding], SDoc, SDoc)
306 dsFExportDynamic mod_name id cconv
307 = newSysLocalDs ty `thenDs` \ fe_id ->
309 -- hack: need to get at the name of the C stub we're about to generate.
310 fe_nm = mkFastString (moduleUserString mod_name ++ "_" ++ toCName fe_id)
312 dsFExport mod_name id export_ty fe_nm cconv True `thenDs` \ (h_code, c_code) ->
313 newSysLocalDs arg_ty `thenDs` \ cback ->
314 dsLookupGlobalValue newStablePtrName `thenDs` \ newStablePtrId ->
316 mk_stbl_ptr_app = mkApps (Var newStablePtrId) [ Type arg_ty, Var cback ]
318 dsLookupGlobalValue bindIOName `thenDs` \ bindIOId ->
319 newSysLocalDs (mkTyConApp stablePtrTyCon [arg_ty]) `thenDs` \ stbl_value ->
322 = mkApps (Var bindIOId)
323 [ Type (mkTyConApp stablePtrTyCon [arg_ty])
330 The arguments to the external function which will
331 create a little bit of (template) code on the fly
332 for allowing the (stable pointed) Haskell closure
333 to be entered using an external calling convention
336 adj_args = [ mkIntLitInt (ccallConvToInt cconv)
338 , mkLit (MachLabel fe_nm)
340 -- name of external entry point providing these services.
341 -- (probably in the RTS.)
342 adjustor = FSLIT("createAdjustor")
344 dsCCall adjustor adj_args PlayRisky False io_res_ty `thenDs` \ ccall_adj ->
345 -- PlayRisky: the adjustor doesn't allocate in the Haskell heap or do a callback
346 let ccall_adj_ty = exprType ccall_adj
347 ccall_io_adj = mkLams [stbl_value] $
348 Note (Coerce io_res_ty ccall_adj_ty)
350 io_app = mkLams tvs $
352 stbl_app ccall_io_adj res_ty
353 fed = (id `setInlinePragma` NeverActive, io_app)
354 -- Never inline the f.e.d. function, because the litlit
355 -- might not be in scope in other modules.
357 returnDs ([fed], h_code, c_code)
361 (tvs,sans_foralls) = tcSplitForAllTys ty
362 ([arg_ty], io_res_ty) = tcSplitFunTys sans_foralls
363 [res_ty] = tcTyConAppArgs io_res_ty
364 -- Must use tcSplit* to see the (IO t), which is a newtype
365 export_ty = mkFunTy (mkTyConApp stablePtrTyCon [arg_ty]) arg_ty
367 toCName :: Id -> String
368 toCName i = showSDoc (pprCode CStyle (ppr (idName i)))
373 \subsection{Generating @foreign export@ stubs}
377 For each @foreign export@ function, a C stub function is generated.
378 The C stub constructs the application of the exported Haskell function
379 using the hugs/ghc rts invocation API.
382 mkFExportCBits :: String
384 -> Maybe Id -- Just==static, Nothing==dynamic
387 -> Bool -- True <=> returns an IO type
390 mkFExportCBits mod_nm c_nm maybe_target arg_htys res_hty is_IO_res_ty cc
391 = (header_bits, c_bits)
393 -- Create up types and names for the real args
394 arg_cnames, arg_ctys :: [SDoc]
395 arg_cnames = mkCArgNames 1 arg_htys
396 arg_ctys = map showStgType arg_htys
398 -- and also for auxiliary ones; the stable ptr in the dynamic case, and
399 -- a slot for the dummy return address in the dynamic + ccall case
400 extra_cnames_and_ctys
401 = case maybe_target of
402 Nothing -> [(text "the_stableptr", text "StgStablePtr")]
405 case (maybe_target, cc) of
406 (Nothing, CCallConv) -> [(text "original_return_addr", text "void*")]
409 all_cnames_and_ctys :: [(SDoc, SDoc)]
411 = extra_cnames_and_ctys ++ zip arg_cnames arg_ctys
413 -- stuff to do with the return type of the C function
414 res_hty_is_unit = res_hty `eqType` unitTy -- Look through any newtypes
416 cResType | res_hty_is_unit = text "void"
417 | otherwise = showStgType res_hty
419 -- Now we can cook up the prototype for the exported function.
420 pprCconv = case cc of
422 StdCallConv -> text (ccallConvAttribute cc)
424 header_bits = ptext SLIT("extern") <+> fun_proto <> semi
426 fun_proto = cResType <+> pprCconv <+> ftext c_nm <>
427 parens (hsep (punctuate comma (map (\(nm,ty) -> ty <+> nm)
428 all_cnames_and_ctys)))
430 -- the target which will form the root of what we ask rts_evalIO to run
432 = case maybe_target of
433 Nothing -> text "(StgClosure*)deRefStablePtr(the_stableptr)"
434 Just hs_fn -> char '&' <> ppr hs_fn <> text "_closure"
436 -- the expression we give to rts_evalIO
438 = foldl appArg the_cfun (zip arg_cnames arg_htys)
440 appArg acc (arg_cname, arg_hty)
442 <> parens (acc <> comma <> mkHObj arg_hty <> parens arg_cname)
444 -- various other bits for inside the fn
445 declareResult = text "HaskellObj ret;"
447 return_what | res_hty_is_unit = empty
448 | otherwise = parens (unpackHObj res_hty <> parens (text "ret"))
450 -- an extern decl for the fn being called
452 = case maybe_target of
454 Just hs_fn -> text "extern StgClosure " <> ppr hs_fn <> text "_closure" <> semi
456 -- finally, the whole darn thing
463 , text "SchedulerStatus rc;"
465 -- create the application + perform it.
466 , text (if is_IO_res_ty then "rc=rts_evalIO" else "rc=rts_eval")
467 <> parens (expr_to_run <+> comma <> text "&ret")
469 , text "rts_checkSchedStatus" <> parens (doubleQuotes (ftext c_nm)
470 <> comma <> text "rc") <> semi
471 , text "return" <> return_what <> semi
476 mkCArgNames :: Int -> [a] -> [SDoc]
477 mkCArgNames n as = zipWith (\ _ n -> text ('a':show n)) as [n..]
479 mkHObj :: Type -> SDoc
480 mkHObj t = text "rts_mk" <> text (showFFIType t)
482 unpackHObj :: Type -> SDoc
483 unpackHObj t = text "rts_get" <> text (showFFIType t)
485 showStgType :: Type -> SDoc
486 showStgType t = text "Hs" <> text (showFFIType t)
488 showFFIType :: Type -> String
489 showFFIType t = getOccString (getName tc)
491 tc = case tcSplitTyConApp_maybe (repType t) of
493 Nothing -> pprPanic "showFFIType" (ppr t)