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 )
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.
63 type Binding = (Id, CoreExpr) -- No rec/nonrec structure;
64 -- the occurrence analyser will sort it all out
67 -> [TypecheckedForeignDecl]
68 -> DsM ( [Id] -- Foreign-exported binders;
69 -- we have to generate code to register these
71 , SDoc -- Header file prototypes for
72 -- "foreign exported" functions.
73 , SDoc -- C stubs to use when calling
74 -- "foreign exported" functions.
75 , [FAST_STRING] -- headers that need to be included
76 -- into C code generated for this module
78 dsForeigns mod_name fos
79 = foldlDs combine ([], [], empty, empty, []) fos
81 combine (acc_feb, acc_f, acc_h, acc_c, acc_header)
82 (ForeignImport id _ spec depr loc)
83 = dsFImport mod_name id spec `thenDs` \(bs, h, c, hd) ->
84 warnDepr depr loc `thenDs` \_ ->
85 returnDs (acc_feb, bs ++ acc_f, h $$ acc_h, c $$ acc_c, hd ++ acc_header)
87 combine (acc_feb, acc_f, acc_h, acc_c, acc_header)
88 (ForeignExport id _ (CExport (CExportStatic ext_nm cconv)) depr loc)
89 = dsFExport mod_name id (idType id)
90 ext_nm cconv False `thenDs` \(h, c) ->
91 warnDepr depr loc `thenDs` \_ ->
92 returnDs (acc_feb, acc_f, h $$ acc_h, c $$ acc_c, acc_header)
94 warnDepr False _ = returnDs ()
95 warnDepr True loc = dsWarn (addShortWarnLocLine loc msg)
97 msg = ptext SLIT("foreign declaration uses deprecated non-standard syntax")
101 %************************************************************************
103 \subsection{Foreign import}
105 %************************************************************************
107 Desugaring foreign imports is just the matter of creating a binding
108 that on its RHS unboxes its arguments, performs the external call
109 (using the @CCallOp@ primop), before boxing the result up and returning it.
111 However, we create a worker/wrapper pair, thus:
113 foreign import f :: Int -> IO Int
115 f x = IO ( \s -> case x of { I# x# ->
116 case fw s x# of { (# s1, y# #) ->
119 fw s x# = ccall f s x#
121 The strictness/CPR analyser won't do this automatically because it doesn't look
122 inside returned tuples; but inlining this wrapper is a Really Good Idea
123 because it exposes the boxing to the call site.
129 -> DsM ([Binding], SDoc, SDoc, [FAST_STRING])
130 dsFImport modName id (CImport cconv safety header lib spec)
131 = dsCImport modName id spec cconv safety `thenDs` \(ids, h, c) ->
132 returnDs (ids, h, c, if _NULL_ header then [] else [header])
133 -- FIXME: the `lib' field is needed for .NET ILX generation when invoking
134 -- routines that are external to the .NET runtime, but GHC doesn't
135 -- support such calls yet; if `_NULL_ lib', the value was not given
136 dsFImport modName id (DNImport spec)
137 = dsFCall modName id (DNCall spec) `thenDs` \(ids, h, c) ->
138 returnDs (ids, h, c, [])
145 -> DsM ([Binding], SDoc, SDoc)
146 dsCImport modName id (CLabel cid) _ _
147 = ASSERT(fromJust resTy `eqType` addrPrimTy) -- typechecker ensures this
148 returnDs ([(id, rhs)], empty, empty)
150 (resTy, foRhs) = resultWrapper (idType id)
151 rhs = foRhs (mkLit (MachLabel cid))
152 dsCImport modName id (CFunction target) cconv safety
153 = dsFCall modName id (CCall (CCallSpec target cconv safety))
154 dsCImport modName id CWrapper cconv _
155 = dsFExportDynamic modName id cconv
159 %************************************************************************
161 \subsection{Foreign calls}
163 %************************************************************************
166 dsFCall mod_Name fn_id fcall
169 (tvs, fun_ty) = tcSplitForAllTys ty
170 (arg_tys, io_res_ty) = tcSplitFunTys fun_ty
171 -- Must use tcSplit* functions because we want to
172 -- see that (IO t) in the corner
174 newSysLocalsDs arg_tys `thenDs` \ args ->
175 mapAndUnzipDs unboxArg (map Var args) `thenDs` \ (val_args, arg_wrappers) ->
178 work_arg_ids = [v | Var v <- val_args] -- All guaranteed to be vars
180 -- These are the ids we pass to boxResult, which are used to decide
181 -- whether to touch# an argument after the call (used to keep
182 -- ForeignObj#s live across a 'safe' foreign import).
183 maybe_arg_ids | unsafe_call fcall = work_arg_ids
186 boxResult maybe_arg_ids io_res_ty `thenDs` \ (ccall_result_ty, res_wrapper) ->
188 getUniqueDs `thenDs` \ ccall_uniq ->
189 getUniqueDs `thenDs` \ work_uniq ->
192 worker_ty = mkForAllTys tvs (mkFunTys (map idType work_arg_ids) ccall_result_ty)
193 the_ccall_app = mkFCall ccall_uniq fcall val_args ccall_result_ty
194 work_rhs = mkLams tvs (mkLams work_arg_ids the_ccall_app)
195 work_id = mkSysLocal (encodeFS SLIT("$wccall")) work_uniq worker_ty
198 work_app = mkApps (mkVarApps (Var work_id) tvs) val_args
199 wrapper_body = foldr ($) (res_wrapper work_app) arg_wrappers
200 wrap_rhs = mkInlineMe (mkLams (tvs ++ args) wrapper_body)
202 returnDs ([(work_id, work_rhs), (fn_id, wrap_rhs)], empty, empty)
204 unsafe_call (CCall (CCallSpec _ _ safety)) = playSafe safety
205 unsafe_call (DNCall _) = False
209 %************************************************************************
211 \subsection{Foreign export}
213 %************************************************************************
215 The function that does most of the work for `@foreign export@' declarations.
216 (see below for the boilerplate code a `@foreign export@' declaration expands
219 For each `@foreign export foo@' in a module M we generate:
221 \item a C function `@foo@', which calls
222 \item a Haskell stub `@M.$ffoo@', which calls
224 the user-written Haskell function `@M.foo@'.
228 -> Id -- Either the exported Id,
229 -- or the foreign-export-dynamic constructor
230 -> Type -- The type of the thing callable from C
231 -> CLabelString -- The name to export to C land
233 -> Bool -- True => foreign export dynamic
234 -- so invoke IO action that's hanging off
235 -- the first argument's stable pointer
236 -> DsM ( SDoc -- contents of Module_stub.h
237 , SDoc -- contents of Module_stub.c
240 dsFExport mod_name fn_id ty ext_name cconv isDyn
243 (tvs,sans_foralls) = tcSplitForAllTys ty
244 (fe_arg_tys', orig_res_ty) = tcSplitFunTys sans_foralls
245 -- We must use tcSplits here, because we want to see
246 -- the (IO t) in the corner of the type!
247 fe_arg_tys | isDyn = tail fe_arg_tys'
248 | otherwise = fe_arg_tys'
250 -- Look at the result type of the exported function, orig_res_ty
251 -- If it's IO t, return (t, True)
252 -- If it's plain t, return (t, False)
253 (case tcSplitTyConApp_maybe orig_res_ty of
254 -- We must use tcSplit here so that we see the (IO t) in
255 -- the type. [IO t is transparent to plain splitTyConApp.]
257 Just (ioTyCon, [res_ty])
258 -> ASSERT( ioTyCon `hasKey` ioTyConKey )
259 -- The function already returns IO t
260 returnDs (res_ty, True)
262 other -> -- The function returns t
263 returnDs (orig_res_ty, False)
265 `thenDs` \ (res_ty, -- t
266 is_IO_res_ty) -> -- Bool
271 = mkFExportCBits (moduleUserString mod) ext_name
272 (if isDyn then Nothing else Just fn_id)
273 fe_arg_tys res_ty is_IO_res_ty cconv
275 returnDs (h_stub, c_stub)
278 @foreign export dynamic@ lets you dress up Haskell IO actions
279 of some fixed type behind an externally callable interface (i.e.,
280 as a C function pointer). Useful for callbacks and stuff.
283 foreign export dynamic f :: (Addr -> Int -> IO Int) -> IO Addr
285 -- Haskell-visible constructor, which is generated from the above:
286 -- SUP: No check for NULL from createAdjustor anymore???
288 f :: (Addr -> Int -> IO Int) -> IO Addr
290 bindIO (newStablePtr cback)
291 (\StablePtr sp# -> IO (\s1# ->
292 case _ccall_ createAdjustor cconv sp# ``f_helper'' s1# of
293 (# s2#, a# #) -> (# s2#, A# a# #)))
295 foreign export "f_helper" f_helper :: StablePtr (Addr -> Int -> IO Int) -> Addr -> Int -> IO Int
296 -- `special' foreign export that invokes the closure pointed to by the
301 dsFExportDynamic :: Module
304 -> DsM ([Binding], SDoc, SDoc)
305 dsFExportDynamic mod_name id cconv
306 = newSysLocalDs ty `thenDs` \ fe_id ->
308 -- hack: need to get at the name of the C stub we're about to generate.
309 fe_nm = _PK_ (moduleUserString mod_name ++ "_" ++ toCName fe_id)
311 dsFExport mod_name id export_ty fe_nm cconv True `thenDs` \ (h_code, c_code) ->
312 newSysLocalDs arg_ty `thenDs` \ cback ->
313 dsLookupGlobalValue newStablePtrName `thenDs` \ newStablePtrId ->
315 mk_stbl_ptr_app = mkApps (Var newStablePtrId) [ Type arg_ty, Var cback ]
317 dsLookupGlobalValue bindIOName `thenDs` \ bindIOId ->
318 newSysLocalDs (mkTyConApp stablePtrTyCon [arg_ty]) `thenDs` \ stbl_value ->
321 = mkApps (Var bindIOId)
322 [ Type (mkTyConApp stablePtrTyCon [arg_ty])
329 The arguments to the external function which will
330 create a little bit of (template) code on the fly
331 for allowing the (stable pointed) Haskell closure
332 to be entered using an external calling convention
335 adj_args = [ mkIntLitInt (ccallConvToInt cconv)
337 , mkLit (MachLabel fe_nm)
339 -- name of external entry point providing these services.
340 -- (probably in the RTS.)
341 adjustor = SLIT("createAdjustor")
343 dsCCall adjustor adj_args PlayRisky False io_res_ty `thenDs` \ ccall_adj ->
344 -- PlayRisky: the adjustor doesn't allocate in the Haskell heap or do a callback
345 let ccall_adj_ty = exprType ccall_adj
346 ccall_io_adj = mkLams [stbl_value] $
347 Note (Coerce io_res_ty ccall_adj_ty)
349 io_app = mkLams tvs $
351 stbl_app ccall_io_adj res_ty
352 fed = (id `setInlinePragma` NeverActive, io_app)
353 -- Never inline the f.e.d. function, because the litlit
354 -- might not be in scope in other modules.
356 returnDs ([fed], h_code, c_code)
360 (tvs,sans_foralls) = tcSplitForAllTys ty
361 ([arg_ty], io_res_ty) = tcSplitFunTys sans_foralls
362 [res_ty] = tcTyConAppArgs io_res_ty
363 -- Must use tcSplit* to see the (IO t), which is a newtype
364 export_ty = mkFunTy (mkTyConApp stablePtrTyCon [arg_ty]) arg_ty
366 toCName :: Id -> String
367 toCName i = showSDoc (pprCode CStyle (ppr (idName i)))
372 \subsection{Generating @foreign export@ stubs}
376 For each @foreign export@ function, a C stub function is generated.
377 The C stub constructs the application of the exported Haskell function
378 using the hugs/ghc rts invocation API.
381 mkFExportCBits :: String
383 -> Maybe Id -- Just==static, Nothing==dynamic
386 -> Bool -- True <=> returns an IO type
389 mkFExportCBits mod_nm c_nm maybe_target arg_htys res_hty is_IO_res_ty cc
390 = (header_bits, c_bits)
392 -- Create up types and names for the real args
393 arg_cnames, arg_ctys :: [SDoc]
394 arg_cnames = mkCArgNames 1 arg_htys
395 arg_ctys = map showStgType arg_htys
397 -- and also for auxiliary ones; the stable ptr in the dynamic case, and
398 -- a slot for the dummy return address in the dynamic + ccall case
399 extra_cnames_and_ctys
400 = case maybe_target of
401 Nothing -> [(text "the_stableptr", text "StgStablePtr")]
404 case (maybe_target, cc) of
405 (Nothing, CCallConv) -> [(text "original_return_addr", text "void*")]
408 all_cnames_and_ctys :: [(SDoc, SDoc)]
410 = extra_cnames_and_ctys ++ zip arg_cnames arg_ctys
412 -- stuff to do with the return type of the C function
413 res_hty_is_unit = res_hty `eqType` unitTy -- Look through any newtypes
415 cResType | res_hty_is_unit = text "void"
416 | otherwise = showStgType res_hty
418 -- Now we can cook up the prototype for the exported function.
419 pprCconv = case cc of
421 StdCallConv -> text (ccallConvAttribute cc)
423 header_bits = ptext SLIT("extern") <+> fun_proto <> semi
425 fun_proto = cResType <+> pprCconv <+> ptext c_nm <>
426 parens (hsep (punctuate comma (map (\(nm,ty) -> ty <+> nm)
427 all_cnames_and_ctys)))
429 -- the target which will form the root of what we ask rts_evalIO to run
431 = case maybe_target of
432 Nothing -> text "(StgClosure*)deRefStablePtr(the_stableptr)"
433 Just hs_fn -> char '&' <> ppr hs_fn <> text "_closure"
435 -- the expression we give to rts_evalIO
437 = foldl appArg the_cfun (zip arg_cnames arg_htys)
439 appArg acc (arg_cname, arg_hty)
441 <> parens (acc <> comma <> mkHObj arg_hty <> parens arg_cname)
443 -- various other bits for inside the fn
444 declareResult = text "HaskellObj ret;"
446 return_what | res_hty_is_unit = empty
447 | otherwise = parens (unpackHObj res_hty <> parens (text "ret"))
449 -- an extern decl for the fn being called
451 = case maybe_target of
453 Just hs_fn -> text "extern StgClosure " <> ppr hs_fn <> text "_closure" <> semi
455 -- finally, the whole darn thing
462 , text "SchedulerStatus rc;"
464 -- create the application + perform it.
465 , text (if is_IO_res_ty then "rc=rts_evalIO" else "rc=rts_eval")
466 <> parens (expr_to_run <+> comma <> text "&ret")
468 , text "rts_checkSchedStatus" <> parens (doubleQuotes (ptext c_nm)
469 <> comma <> text "rc") <> semi
470 , text "return" <> return_what <> semi
475 mkCArgNames :: Int -> [a] -> [SDoc]
476 mkCArgNames n as = zipWith (\ _ n -> text ('a':show n)) as [n..]
478 mkHObj :: Type -> SDoc
479 mkHObj t = text "rts_mk" <> text (showFFIType t)
481 unpackHObj :: Type -> SDoc
482 unpackHObj t = text "rts_get" <> text (showFFIType t)
484 showStgType :: Type -> SDoc
485 showStgType t = text "Hs" <> text (showFFIType t)
487 showFFIType :: Type -> String
488 showFFIType t = getOccString (getName tc)
490 tc = case tcSplitTyConApp_maybe (repType t) of
492 Nothing -> pprPanic "showFFIType" (ppr t)