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, mkVanillaGlobal, mkSysLocal,
24 import IdInfo ( vanillaIdInfo )
25 import Literal ( Literal(..) )
26 import Module ( Module, moduleUserString )
27 import Name ( mkGlobalName, nameModule, nameOccName, getOccString,
28 mkForeignExportOcc, isLocalName,
31 import OccName ( encodeFS )
32 import Type ( repType, eqType )
33 import TcType ( Type, mkFunTys, mkForAllTys, mkTyConApp,
35 tcSplitForAllTys, tcSplitFunTys, tcTyConAppArgs,
36 tcSplitTyConApp_maybe, tcSplitAppTy,
40 import ForeignCall ( ForeignCall(..), CCallSpec(..),
43 CCallConv(..), ccallConvToInt,
46 import CStrings ( CLabelString )
47 import TysWiredIn ( addrTy, unitTy, stablePtrTyCon )
48 import TysPrim ( addrPrimTy )
49 import PrelNames ( hasKey, ioTyConKey, deRefStablePtrName, newStablePtrName,
50 bindIOName, returnIOName
52 import BasicTypes ( Activation( NeverActive ) )
53 import ErrUtils ( addShortWarnLocLine )
55 import Maybe ( fromJust )
58 Desugaring of @foreign@ declarations is naturally split up into
59 parts, an @import@ and an @export@ part. A @foreign import@
62 foreign import cc nm f :: prim_args -> IO prim_res
66 f :: prim_args -> IO prim_res
67 f a1 ... an = _ccall_ nm cc a1 ... an
69 so we reuse the desugaring code in @DsCCall@ to deal with these.
72 type Binding = (Id, CoreExpr) -- No rec/nonrec structure;
73 -- the occurrence analyser will sort it all out
76 -> [TypecheckedForeignDecl]
77 -> DsM ( [Id] -- Foreign-exported binders;
78 -- we have to generate code to register these
80 , SDoc -- Header file prototypes for
81 -- "foreign exported" functions.
82 , SDoc -- C stubs to use when calling
83 -- "foreign exported" functions.
84 , [FAST_STRING] -- headers that need to be included
85 -- into C code generated for this module
87 dsForeigns mod_name fos
88 = foldlDs combine ([], [], empty, empty, []) fos
90 combine (acc_feb, acc_f, acc_h, acc_c, acc_header)
91 (ForeignImport id _ spec depr loc)
92 = dsFImport mod_name id spec `thenDs` \(bs, h, c, hd) ->
93 warnDepr depr loc `thenDs` \_ ->
94 returnDs (acc_feb, bs ++ acc_f, h $$ acc_h, c $$ acc_c, hd ++ acc_header)
96 combine (acc_feb, acc_f, acc_h, acc_c, acc_header)
97 (ForeignExport id _ (CExport (CExportStatic ext_nm cconv)) depr loc)
98 = dsFExport mod_name id (idType id)
99 ext_nm cconv False `thenDs` \(h, c) ->
100 warnDepr depr loc `thenDs` \_ ->
101 returnDs (acc_feb, acc_f, h $$ acc_h, c $$ acc_c, acc_header)
103 warnDepr False _ = returnDs ()
104 warnDepr True loc = dsWarn (addShortWarnLocLine loc msg)
106 msg = ptext SLIT("foreign declaration uses deprecated non-standard syntax")
110 %************************************************************************
112 \subsection{Foreign import}
114 %************************************************************************
116 Desugaring foreign imports is just the matter of creating a binding
117 that on its RHS unboxes its arguments, performs the external call
118 (using the @CCallOp@ primop), before boxing the result up and returning it.
120 However, we create a worker/wrapper pair, thus:
122 foreign import f :: Int -> IO Int
124 f x = IO ( \s -> case x of { I# x# ->
125 case fw s x# of { (# s1, y# #) ->
128 fw s x# = ccall f s x#
130 The strictness/CPR analyser won't do this automatically because it doesn't look
131 inside returned tuples; but inlining this wrapper is a Really Good Idea
132 because it exposes the boxing to the call site.
138 -> DsM ([Binding], SDoc, SDoc, [FAST_STRING])
139 dsFImport modName id (CImport cconv safety header lib spec)
140 = dsCImport modName id spec cconv safety `thenDs` \(ids, h, c) ->
141 returnDs (ids, h, c, if _NULL_ header then [] else [header])
142 -- FIXME: the `lib' field is needed for .NET ILX generation when invoking
143 -- routines that are external to the .NET runtime, but GHC doesn't
144 -- support such calls yet; if `_NULL_ lib', the value was not given
145 dsFImport modName id (DNImport spec)
146 = dsFCall modName id (DNCall spec) `thenDs` \(ids, h, c) ->
147 returnDs (ids, h, c, [])
154 -> DsM ([Binding], SDoc, SDoc)
155 dsCImport modName id (CLabel cid) _ _
156 = ASSERT(fromJust resTy `eqType` addrPrimTy) -- typechecker ensures this
157 returnDs ([(id, rhs)], empty, empty)
159 (resTy, foRhs) = resultWrapper (idType id)
160 rhs = foRhs (mkLit (MachLabel cid))
161 dsCImport modName id (CFunction target) cconv safety
162 = dsFCall modName id (CCall (CCallSpec target cconv safety))
163 dsCImport modName id CWrapper cconv _
164 = dsFExportDynamic modName id cconv
168 %************************************************************************
170 \subsection{Foreign calls}
172 %************************************************************************
175 dsFCall mod_Name fn_id fcall
178 (tvs, fun_ty) = tcSplitForAllTys ty
179 (arg_tys, io_res_ty) = tcSplitFunTys fun_ty
180 -- Must use tcSplit* functions because we want to
181 -- see that (IO t) in the corner
183 newSysLocalsDs arg_tys `thenDs` \ args ->
184 mapAndUnzipDs unboxArg (map Var args) `thenDs` \ (val_args, arg_wrappers) ->
187 work_arg_ids = [v | Var v <- val_args] -- All guaranteed to be vars
189 -- These are the ids we pass to boxResult, which are used to decide
190 -- whether to touch# an argument after the call (used to keep
191 -- ForeignObj#s live across a 'safe' foreign import).
192 maybe_arg_ids | unsafe_call fcall = work_arg_ids
195 boxResult maybe_arg_ids io_res_ty `thenDs` \ (ccall_result_ty, res_wrapper) ->
197 getUniqueDs `thenDs` \ ccall_uniq ->
198 getUniqueDs `thenDs` \ work_uniq ->
201 worker_ty = mkForAllTys tvs (mkFunTys (map idType work_arg_ids) ccall_result_ty)
202 the_ccall_app = mkFCall ccall_uniq fcall val_args ccall_result_ty
203 work_rhs = mkLams tvs (mkLams work_arg_ids the_ccall_app)
204 work_id = mkSysLocal (encodeFS SLIT("$wccall")) work_uniq worker_ty
207 work_app = mkApps (mkVarApps (Var work_id) tvs) val_args
208 wrapper_body = foldr ($) (res_wrapper work_app) arg_wrappers
209 wrap_rhs = mkInlineMe (mkLams (tvs ++ args) wrapper_body)
211 returnDs ([(work_id, work_rhs), (fn_id, wrap_rhs)], empty, empty)
213 unsafe_call (CCall (CCallSpec _ _ safety)) = playSafe safety
214 unsafe_call (DNCall _) = False
218 %************************************************************************
220 \subsection{Foreign export}
222 %************************************************************************
224 The function that does most of the work for `@foreign export@' declarations.
225 (see below for the boilerplate code a `@foreign export@' declaration expands
228 For each `@foreign export foo@' in a module M we generate:
230 \item a C function `@foo@', which calls
231 \item a Haskell stub `@M.$ffoo@', which calls
233 the user-written Haskell function `@M.foo@'.
237 -> Id -- Either the exported Id,
238 -- or the foreign-export-dynamic constructor
239 -> Type -- The type of the thing callable from C
240 -> CLabelString -- The name to export to C land
242 -> Bool -- True => foreign export dynamic
243 -- so invoke IO action that's hanging off
244 -- the first argument's stable pointer
245 -> DsM ( SDoc -- contents of Module_stub.h
246 , SDoc -- contents of Module_stub.c
249 dsFExport mod_name fn_id ty ext_name cconv isDyn
252 (tvs,sans_foralls) = tcSplitForAllTys ty
253 (fe_arg_tys', orig_res_ty) = tcSplitFunTys sans_foralls
254 -- We must use tcSplits here, because we want to see
255 -- the (IO t) in the corner of the type!
256 fe_arg_tys | isDyn = tail fe_arg_tys'
257 | otherwise = fe_arg_tys'
259 -- Look at the result type of the exported function, orig_res_ty
260 -- If it's IO t, return (t, True)
261 -- If it's plain t, return (t, False)
262 (case tcSplitTyConApp_maybe orig_res_ty of
263 -- We must use tcSplit here so that we see the (IO t) in
264 -- the type. [IO t is transparent to plain splitTyConApp.]
266 Just (ioTyCon, [res_ty])
267 -> ASSERT( ioTyCon `hasKey` ioTyConKey )
268 -- The function already returns IO t
269 returnDs (res_ty, True)
271 other -> -- The function returns t
272 returnDs (orig_res_ty, False)
274 `thenDs` \ (res_ty, -- t
275 is_IO_res_ty) -> -- Bool
280 = mkFExportCBits (moduleUserString mod) ext_name
281 (if isDyn then Nothing else Just fn_id)
282 fe_arg_tys res_ty is_IO_res_ty cconv
284 returnDs (h_stub, c_stub)
287 @foreign export dynamic@ lets you dress up Haskell IO actions
288 of some fixed type behind an externally callable interface (i.e.,
289 as a C function pointer). Useful for callbacks and stuff.
292 foreign export dynamic f :: (Addr -> Int -> IO Int) -> IO Addr
294 -- Haskell-visible constructor, which is generated from the above:
295 -- SUP: No check for NULL from createAdjustor anymore???
297 f :: (Addr -> Int -> IO Int) -> IO Addr
299 bindIO (newStablePtr cback)
300 (\StablePtr sp# -> IO (\s1# ->
301 case _ccall_ createAdjustor cconv sp# ``f_helper'' s1# of
302 (# s2#, a# #) -> (# s2#, A# a# #)))
304 foreign export "f_helper" f_helper :: StablePtr (Addr -> Int -> IO Int) -> Addr -> Int -> IO Int
305 -- `special' foreign export that invokes the closure pointed to by the
310 dsFExportDynamic :: Module
313 -> DsM ([Binding], SDoc, SDoc)
314 dsFExportDynamic mod_name id cconv
315 = newSysLocalDs ty `thenDs` \ fe_id ->
317 -- hack: need to get at the name of the C stub we're about to generate.
318 fe_nm = _PK_ (moduleUserString mod_name ++ "_" ++ toCName fe_id)
320 dsFExport mod_name id export_ty fe_nm cconv True `thenDs` \ (h_code, c_code) ->
321 newSysLocalDs arg_ty `thenDs` \ cback ->
322 dsLookupGlobalValue newStablePtrName `thenDs` \ newStablePtrId ->
324 mk_stbl_ptr_app = mkApps (Var newStablePtrId) [ Type arg_ty, Var cback ]
326 dsLookupGlobalValue bindIOName `thenDs` \ bindIOId ->
327 newSysLocalDs (mkTyConApp stablePtrTyCon [arg_ty]) `thenDs` \ stbl_value ->
330 = mkApps (Var bindIOId)
331 [ Type (mkTyConApp stablePtrTyCon [arg_ty])
338 The arguments to the external function which will
339 create a little bit of (template) code on the fly
340 for allowing the (stable pointed) Haskell closure
341 to be entered using an external calling convention
344 adj_args = [ mkIntLitInt (ccallConvToInt cconv)
346 , mkLit (MachLabel fe_nm)
348 -- name of external entry point providing these services.
349 -- (probably in the RTS.)
350 adjustor = SLIT("createAdjustor")
352 dsCCall adjustor adj_args PlayRisky False io_res_ty `thenDs` \ ccall_adj ->
353 -- PlayRisky: the adjustor doesn't allocate in the Haskell heap or do a callback
354 let ccall_adj_ty = exprType ccall_adj
355 ccall_io_adj = mkLams [stbl_value] $
356 Note (Coerce io_res_ty ccall_adj_ty)
358 io_app = mkLams tvs $
360 stbl_app ccall_io_adj res_ty
361 fed = (id `setInlinePragma` NeverActive, io_app)
362 -- Never inline the f.e.d. function, because the litlit
363 -- might not be in scope in other modules.
365 returnDs ([fed], h_code, c_code)
369 (tvs,sans_foralls) = tcSplitForAllTys ty
370 ([arg_ty], io_res_ty) = tcSplitFunTys sans_foralls
371 [res_ty] = tcTyConAppArgs io_res_ty
372 -- Must use tcSplit* to see the (IO t), which is a newtype
373 export_ty = mkFunTy (mkTyConApp stablePtrTyCon [arg_ty]) arg_ty
375 toCName :: Id -> String
376 toCName i = showSDoc (pprCode CStyle (ppr (idName i)))
381 \subsection{Generating @foreign export@ stubs}
385 For each @foreign export@ function, a C stub function is generated.
386 The C stub constructs the application of the exported Haskell function
387 using the hugs/ghc rts invocation API.
390 mkFExportCBits :: String
392 -> Maybe Id -- Just==static, Nothing==dynamic
395 -> Bool -- True <=> returns an IO type
398 mkFExportCBits mod_nm c_nm maybe_target arg_htys res_hty is_IO_res_ty cc
399 = (header_bits, c_bits)
401 -- Create up types and names for the real args
402 arg_cnames, arg_ctys :: [SDoc]
403 arg_cnames = mkCArgNames 1 arg_htys
404 arg_ctys = map showStgType arg_htys
406 -- and also for auxiliary ones; the stable ptr in the dynamic case, and
407 -- a slot for the dummy return address in the dynamic + ccall case
408 extra_cnames_and_ctys
409 = case maybe_target of
410 Nothing -> [(text "the_stableptr", text "StgStablePtr")]
413 case (maybe_target, cc) of
414 (Nothing, CCallConv) -> [(text "original_return_addr", text "void*")]
417 all_cnames_and_ctys :: [(SDoc, SDoc)]
419 = extra_cnames_and_ctys ++ zip arg_cnames arg_ctys
421 -- stuff to do with the return type of the C function
422 res_hty_is_unit = res_hty `eqType` unitTy -- Look through any newtypes
424 cResType | res_hty_is_unit = text "void"
425 | otherwise = showStgType res_hty
427 -- Now we can cook up the prototype for the exported function.
428 pprCconv = case cc of
430 StdCallConv -> text (ccallConvAttribute cc)
432 header_bits = ptext SLIT("extern") <+> fun_proto <> semi
434 fun_proto = cResType <+> pprCconv <+> ptext c_nm <>
435 parens (hsep (punctuate comma (map (\(nm,ty) -> ty <+> nm)
436 all_cnames_and_ctys)))
438 -- the target which will form the root of what we ask rts_evalIO to run
440 = case maybe_target of
441 Nothing -> text "(StgClosure*)deRefStablePtr(the_stableptr)"
442 Just hs_fn -> ppr hs_fn <> text "_closure"
444 -- the expression we give to rts_evalIO
446 = foldl appArg the_cfun (zip arg_cnames arg_htys)
448 appArg acc (arg_cname, arg_hty)
450 <> parens (acc <> comma <> mkHObj arg_hty <> parens arg_cname)
452 -- various other bits for inside the fn
453 declareResult = text "HaskellObj ret;"
455 return_what | res_hty_is_unit = empty
456 | otherwise = parens (unpackHObj res_hty <> parens (text "ret"))
458 -- an extern decl for the fn being called
460 = case maybe_target of
462 Just hs_fn -> text "extern StgClosure* " <> ppr hs_fn <> text "_closure" <> semi
464 -- finally, the whole darn thing
471 , text "SchedulerStatus rc;"
473 -- create the application + perform it.
474 , text (if is_IO_res_ty then "rc=rts_evalIO" else "rc=rts_eval")
475 <> parens (expr_to_run <+> comma <> text "&ret")
477 , text "rts_checkSchedStatus" <> parens (doubleQuotes (ptext c_nm)
478 <> comma <> text "rc") <> semi
479 , text "return" <> return_what <> semi
484 mkCArgNames :: Int -> [a] -> [SDoc]
485 mkCArgNames n as = zipWith (\ _ n -> text ('a':show n)) as [n..]
487 mkHObj :: Type -> SDoc
488 mkHObj t = text "rts_mk" <> text (showFFIType t)
490 unpackHObj :: Type -> SDoc
491 unpackHObj t = text "rts_get" <> text (showFFIType t)
493 showStgType :: Type -> SDoc
494 showStgType t = text "Hs" <> text (showFFIType t)
496 showFFIType :: Type -> String
497 showFFIType t = getOccString (getName tc)
499 tc = case tcSplitTyConApp_maybe (repType t) of
501 Nothing -> pprPanic "showFFIType" (ppr t)