[project @ 2001-05-22 13:43:14 by simonpj]
[ghc-hetmet.git] / ghc / compiler / deSugar / DsForeign.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1998
3 %
4 \section[DsCCall]{Desugaring \tr{foreign} declarations}
5
6 Expanding out @foreign import@ and @foreign export@ declarations.
7
8 \begin{code}
9 module DsForeign ( dsForeigns ) where
10
11 #include "HsVersions.h"
12
13 import CoreSyn
14
15 import DsCCall          ( dsCCall, mkFCall, boxResult, unboxArg, resultWrapper )
16 import DsMonad
17
18 import HsSyn            ( ExtName(..), ForeignDecl(..), isDynamicExtName, ForKind(..) )
19 import HsDecls          ( extNameStatic )
20 import TcHsSyn          ( TypecheckedForeignDecl )
21 import CoreUtils        ( exprType, mkInlineMe )
22 import Id               ( Id, idType, idName, mkVanillaGlobal, mkSysLocal,
23                           setInlinePragma )
24 import IdInfo           ( neverInlinePrag, vanillaIdInfo )
25 import Literal          ( Literal(..) )
26 import Module           ( Module, moduleUserString )
27 import Name             ( mkGlobalName, nameModule, nameOccName, getOccString, 
28                           mkForeignExportOcc, isLocalName,
29                           NamedThing(..),
30                         )
31 import Type             ( repType, splitTyConApp_maybe,
32                           splitFunTys, splitForAllTys,
33                           Type, mkFunTys, mkForAllTys, mkTyConApp,
34                           mkFunTy, splitAppTy, applyTy, funResultTy
35                         )
36 import ForeignCall      ( ForeignCall(..), CCallSpec(..), 
37                           Safety(..), playSafe,
38                           CCallTarget(..), dynamicTarget,
39                           CCallConv(..), ccallConvToInt
40                         )
41 import TysWiredIn       ( unitTy, addrTy, stablePtrTyCon )
42 import TysPrim          ( addrPrimTy )
43 import PrelNames        ( hasKey, ioTyConKey, deRefStablePtrName, newStablePtrName,
44                           bindIOName, returnIOName
45                         )
46 import Outputable
47
48 import Maybe            ( fromJust )
49 \end{code}
50
51 Desugaring of @foreign@ declarations is naturally split up into
52 parts, an @import@ and an @export@  part. A @foreign import@ 
53 declaration
54 \begin{verbatim}
55   foreign import cc nm f :: prim_args -> IO prim_res
56 \end{verbatim}
57 is the same as
58 \begin{verbatim}
59   f :: prim_args -> IO prim_res
60   f a1 ... an = _ccall_ nm cc a1 ... an
61 \end{verbatim}
62 so we reuse the desugaring code in @DsCCall@ to deal with these.
63
64 \begin{code}
65 type Binding = (Id, CoreExpr)   -- No rec/nonrec structure;
66                                 -- the occurrence analyser will sort it all out
67
68 dsForeigns :: Module
69            -> [TypecheckedForeignDecl] 
70            -> DsM ( [Id]                -- Foreign-exported binders; 
71                                         -- we have to generate code to register these
72                   , [Binding]
73                   , SDoc              -- Header file prototypes for
74                                       -- "foreign exported" functions.
75                   , SDoc              -- C stubs to use when calling
76                                       -- "foreign exported" functions.
77                   )
78 dsForeigns mod_name fos = foldlDs combine ([], [], empty, empty) fos
79  where
80   combine (acc_feb, acc_f, acc_h, acc_c) fo@(ForeignDecl i imp_exp _ ext_nm cconv _) 
81     | isForeignImport =   -- foreign import (dynamic)?
82         dsFImport i (idType i) uns ext_nm cconv  `thenDs` \ bs -> 
83         returnDs (acc_feb, bs ++ acc_f, acc_h, acc_c)
84     | isForeignLabel = 
85         dsFLabel i (idType i) ext_nm `thenDs` \ b -> 
86         returnDs (acc_feb, b:acc_f, acc_h, acc_c)
87     | isDynamicExtName ext_nm =
88         dsFExportDynamic i (idType i) mod_name ext_nm cconv  `thenDs` \ (feb,bs,h,c) -> 
89         returnDs (feb:acc_feb, bs ++ acc_f, h $$ acc_h, c $$ acc_c)
90
91     | otherwise        =  -- foreign export
92         dsFExport i (idType i) mod_name ext_nm cconv False   `thenDs` \ (feb,fe,h,c) ->
93         returnDs (feb:acc_feb, fe:acc_f, h $$ acc_h, c $$ acc_c)
94    where
95     isForeignImport = 
96         case imp_exp of
97           FoImport _ -> True
98           _          -> False
99
100     isForeignLabel = 
101         case imp_exp of
102           FoLabel -> True
103           _       -> False
104
105     FoImport uns = imp_exp
106 \end{code}
107
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.
111
112 However, we create a worker/wrapper pair, thus:
113
114         foreign import f :: Int -> IO Int
115 ==>
116         f x = IO ( \s -> case x of { I# x# ->
117                          case fw s x# of { (# s1, y# #) ->
118                          (# s1, I# y# #)}})
119
120         fw s x# = ccall f s x#
121
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.
125                         
126
127 \begin{code}
128 dsFImport :: Id
129           -> Type               -- Type of foreign import.
130           -> Safety             -- Whether can re-enter the Haskell RTS, do GC etc
131           -> ExtName
132           -> CCallConv
133           -> DsM [Binding]
134 dsFImport fn_id ty safety ext_name cconv 
135   = let
136         (tvs, fun_ty)        = splitForAllTys ty
137         (arg_tys, io_res_ty) = splitFunTys fun_ty
138     in
139     newSysLocalsDs arg_tys                      `thenDs` \ args ->
140     mapAndUnzipDs unboxArg (map Var args)       `thenDs` \ (val_args, arg_wrappers) ->
141
142     let
143         work_arg_ids  = [v | Var v <- val_args] -- All guaranteed to be vars
144
145         -- These are the ids we pass to boxResult, which are used to decide
146         -- whether to touch# an argument after the call (used to keep
147         -- ForeignObj#s live across a 'safe' foreign import).
148         maybe_arg_ids | playSafe safety = work_arg_ids
149                       | otherwise       = []
150     in
151     boxResult maybe_arg_ids io_res_ty           `thenDs` \ (ccall_result_ty, res_wrapper) ->
152
153     getUniqueDs                                 `thenDs` \ ccall_uniq ->
154     getUniqueDs                                 `thenDs` \ work_uniq ->
155     let
156         lbl = case ext_name of
157                 Dynamic      -> dynamicTarget
158                 ExtName fs _ -> StaticTarget fs
159
160         -- Build the worker
161         worker_ty     = mkForAllTys tvs (mkFunTys (map idType work_arg_ids) ccall_result_ty)
162         the_ccall     = CCall (CCallSpec lbl cconv safety False)
163         the_ccall_app = mkFCall ccall_uniq the_ccall val_args ccall_result_ty
164         work_rhs      = mkLams tvs (mkLams work_arg_ids the_ccall_app)
165         work_id       = mkSysLocal SLIT("$wccall") work_uniq worker_ty
166
167         -- Build the wrapper
168         work_app     = mkApps (mkVarApps (Var work_id) tvs) val_args
169         wrapper_body = foldr ($) (res_wrapper work_app) arg_wrappers
170         wrap_rhs     = mkInlineMe (mkLams (tvs ++ args) wrapper_body)
171     in
172     returnDs [(work_id, work_rhs), (fn_id, wrap_rhs)]
173 \end{code}
174
175 Foreign labels 
176
177 \begin{code}
178 dsFLabel :: Id -> Type -> ExtName -> DsM Binding
179 dsFLabel nm ty ext_name = 
180    ASSERT(fromJust res_ty == addrPrimTy) -- typechecker ensures this
181    returnDs (nm, fo_rhs (mkLit (MachLabel enm)))
182   where
183    (res_ty, fo_rhs) = resultWrapper ty
184    enm    = extNameStatic ext_name
185 \end{code}
186
187 The function that does most of the work for `@foreign export@' declarations.
188 (see below for the boilerplate code a `@foreign export@' declaration expands
189  into.)
190
191 For each `@foreign export foo@' in a module M we generate:
192 \begin{itemize}
193 \item a C function `@foo@', which calls
194 \item a Haskell stub `@M.$ffoo@', which calls
195 \end{itemize}
196 the user-written Haskell function `@M.foo@'.
197
198 \begin{code}
199 dsFExport :: Id
200           -> Type               -- Type of foreign export.
201           -> Module
202           -> ExtName
203           -> CCallConv
204           -> Bool               -- True => invoke IO action that's hanging off 
205                                 -- the first argument's stable pointer
206           -> DsM ( Id           -- The foreign-exported Id
207                  , Binding
208                  , SDoc
209                  , SDoc
210                  )
211 dsFExport fn_id ty mod_name ext_name cconv isDyn
212   =     -- BUILD THE returnIO WRAPPER, if necessary
213         -- Look at the result type of the exported function, orig_res_ty
214         -- If it's IO t, return         (\x.x,          IO t, t)
215         -- If it's plain t, return      (\x.returnIO x, IO t, t)
216      (case splitTyConApp_maybe orig_res_ty of
217         Just (ioTyCon, [res_ty])
218               -> ASSERT( ioTyCon `hasKey` ioTyConKey )
219                         -- The function already returns IO t
220                  returnDs (\body -> body, orig_res_ty, res_ty)
221
222         other ->        -- The function returns t, so wrap the call in returnIO
223                  dsLookupGlobalValue returnIOName       `thenDs` \ retIOId ->
224                  returnDs (\body -> mkApps (Var retIOId) [Type orig_res_ty, body],
225                            funResultTy (applyTy (idType retIOId) orig_res_ty), 
226                                 -- We don't have ioTyCon conveniently to hand
227                            orig_res_ty)
228
229      )          `thenDs` \ (return_io_wrapper,  -- Either identity or returnIO
230                             io_res_ty,          -- IO t
231                             res_ty) ->          -- t
232
233
234         -- BUILD THE deRefStablePtr WRAPPER, if necessary
235      (if isDyn then 
236         newSysLocalDs stbl_ptr_ty                       `thenDs` \ stbl_ptr ->
237         newSysLocalDs stbl_ptr_to_ty                    `thenDs` \ stbl_value ->
238         dsLookupGlobalValue deRefStablePtrName          `thenDs` \ deRefStablePtrId ->
239         dsLookupGlobalValue bindIOName                  `thenDs` \ bindIOId ->
240         let
241          the_deref_app = mkApps (Var deRefStablePtrId)
242                                 [ Type stbl_ptr_to_ty, Var stbl_ptr ]
243
244          stbl_app cont = mkApps (Var bindIOId)
245                                 [ Type stbl_ptr_to_ty
246                                 , Type res_ty
247                                 , the_deref_app
248                                 , mkLams [stbl_value] cont]
249         in
250         returnDs (stbl_value, stbl_app, stbl_ptr)
251       else
252         returnDs (fn_id, 
253                   \ body -> body,
254                   panic "stbl_ptr"  -- should never be touched.
255                   ))                    `thenDs` \ (i, getFun_wrapper, stbl_ptr) ->
256
257
258         -- BUILD THE HELPER
259      getModuleDs                        `thenDs` \ mod -> 
260      getUniqueDs                        `thenDs` \ uniq ->
261      getSrcLocDs                        `thenDs` \ src_loc ->
262      newSysLocalsDs fe_arg_tys          `thenDs` \ fe_args ->
263      let
264         wrapper_args | isDyn      = stbl_ptr:fe_args
265                      | otherwise  = fe_args
266
267         wrapper_arg_tys | isDyn      = stbl_ptr_ty:fe_arg_tys
268                         | otherwise  = fe_arg_tys
269
270         helper_ty =  mkForAllTys tvs $
271                      mkFunTys wrapper_arg_tys io_res_ty
272
273         f_helper_glob = mkVanillaGlobal helper_name helper_ty vanillaIdInfo
274                       where
275                         name                = idName fn_id
276                         mod     
277                          | isLocalName name = mod_name
278                          | otherwise        = nameModule name
279
280                         occ                 = mkForeignExportOcc (nameOccName name)
281                         helper_name         = mkGlobalName uniq mod occ src_loc
282
283         the_app = getFun_wrapper (return_io_wrapper (mkVarApps (Var i) (tvs ++ fe_args)))
284         the_body = mkLams (tvs ++ wrapper_args) the_app
285         c_nm     = extNameStatic ext_name
286   
287         (h_stub, c_stub) = fexportEntry (moduleUserString mod)
288                                       c_nm f_helper_glob
289                                       wrapper_arg_tys res_ty cconv isDyn
290      in
291      returnDs (f_helper_glob, (f_helper_glob, the_body), h_stub, c_stub)
292
293   where
294    (tvs,sans_foralls)                   = splitForAllTys ty
295    (fe_arg_tys', orig_res_ty)           = splitFunTys sans_foralls
296
297    (_, stbl_ptr_ty')                    = splitForAllTys stbl_ptr_ty
298    (_, stbl_ptr_to_ty)                  = splitAppTy stbl_ptr_ty'
299
300    fe_arg_tys | isDyn     = tail fe_arg_tys'
301               | otherwise = fe_arg_tys'
302
303    stbl_ptr_ty | isDyn     = head fe_arg_tys'
304                | otherwise = error "stbl_ptr_ty"
305 \end{code}
306
307 @foreign export dynamic@ lets you dress up Haskell IO actions
308 of some fixed type behind an externally callable interface (i.e.,
309 as a C function pointer). Useful for callbacks and stuff.
310
311 \begin{verbatim}
312 foreign export dynamic f :: (Addr -> Int -> IO Int) -> IO Addr
313
314 -- Haskell-visible constructor, which is generated from the above:
315 -- SUP: No check for NULL from createAdjustor anymore???
316
317 f :: (Addr -> Int -> IO Int) -> IO Addr
318 f cback =
319    bindIO (newStablePtr cback)
320           (\StablePtr sp# -> IO (\s1# ->
321               case _ccall_ createAdjustor cconv sp# ``f_helper'' s1# of
322                  (# s2#, a# #) -> (# s2#, A# a# #)))
323
324 foreign export "f_helper" f_helper :: StablePtr (Addr -> Int -> IO Int) -> Addr -> Int -> IO Int
325 -- `special' foreign export that invokes the closure pointed to by the
326 -- first argument.
327 \end{verbatim}
328
329 \begin{code}
330 dsFExportDynamic :: Id
331                  -> Type                -- Type of foreign export.
332                  -> Module
333                  -> ExtName
334                  -> CCallConv
335                  -> DsM (Id, [Binding], SDoc, SDoc)
336 dsFExportDynamic i ty mod_name ext_name cconv =
337      newSysLocalDs ty                                    `thenDs` \ fe_id ->
338      let 
339         -- hack: need to get at the name of the C stub we're about to generate.
340        fe_nm       = moduleUserString mod_name ++ "_" ++ toCName fe_id
341        fe_ext_name = ExtName (_PK_ fe_nm) Nothing
342      in
343      dsFExport  i export_ty mod_name fe_ext_name cconv True
344         `thenDs` \ (feb, fe, h_code, c_code) ->
345      newSysLocalDs arg_ty                       `thenDs` \ cback ->
346      dsLookupGlobalValue newStablePtrName       `thenDs` \ newStablePtrId ->
347      let
348         mk_stbl_ptr_app    = mkApps (Var newStablePtrId) [ Type arg_ty, Var cback ]
349      in
350      dsLookupGlobalValue bindIOName                     `thenDs` \ bindIOId ->
351      newSysLocalDs (mkTyConApp stablePtrTyCon [arg_ty]) `thenDs` \ stbl_value ->
352      let
353       stbl_app cont ret_ty 
354         = mkApps (Var bindIOId)
355                  [ Type (mkTyConApp stablePtrTyCon [arg_ty])
356                  , Type ret_ty
357                  , mk_stbl_ptr_app
358                  , cont
359                  ]
360
361        {-
362         The arguments to the external function which will
363         create a little bit of (template) code on the fly
364         for allowing the (stable pointed) Haskell closure
365         to be entered using an external calling convention
366         (stdcall, ccall).
367        -}
368       adj_args      = [ mkIntLitInt (ccallConvToInt cconv)
369                       , Var stbl_value
370                       , mkLit (MachLabel (_PK_ fe_nm))
371                       ]
372         -- name of external entry point providing these services.
373         -- (probably in the RTS.) 
374       adjustor      = SLIT("createAdjustor")
375      in
376      dsCCall adjustor adj_args PlayRisky False io_res_ty        `thenDs` \ ccall_adj ->
377         -- PlayRisky: the adjustor doesn't allocate in the Haskell heap or do a callback
378      let ccall_adj_ty = exprType ccall_adj
379          ccall_io_adj = mkLams [stbl_value]                  $
380                         Note (Coerce io_res_ty ccall_adj_ty)
381                              ccall_adj
382          io_app = mkLams tvs     $
383                   mkLams [cback] $
384                   stbl_app ccall_io_adj res_ty
385          fed = (i `setInlinePragma` neverInlinePrag, io_app)
386                 -- Never inline the f.e.d. function, because the litlit
387                 -- might not be in scope in other modules.
388      in
389      returnDs (feb, [fed, fe], h_code, c_code)
390
391  where
392   (tvs,sans_foralls)               = splitForAllTys ty
393   ([arg_ty], io_res_ty)            = splitFunTys sans_foralls
394   Just (ioTyCon, [res_ty])         = splitTyConApp_maybe io_res_ty
395   export_ty                        = mkFunTy (mkTyConApp stablePtrTyCon [arg_ty]) arg_ty
396
397 toCName :: Id -> String
398 toCName i = showSDoc (pprCode CStyle (ppr (idName i)))
399 \end{code}
400
401 %*
402 %
403 \subsection{Generating @foreign export@ stubs}
404 %
405 %*
406
407 For each @foreign export@ function, a C stub function is generated.
408 The C stub constructs the application of the exported Haskell function 
409 using the hugs/ghc rts invocation API.
410
411 \begin{code}
412 fexportEntry :: String
413              -> FAST_STRING
414              -> Id 
415              -> [Type] 
416              -> Type 
417              -> CCallConv 
418              -> Bool
419              -> (SDoc, SDoc)
420 fexportEntry mod_nm c_nm helper args res_ty cc isDyn = (header_bits, c_bits)
421  where
422    -- name of the (Haskell) helper function generated by the desugarer.
423   h_nm      = ppr helper <> text "_closure"
424    -- prototype for the exported function.
425   header_bits = ptext SLIT("extern") <+> fun_proto <> semi
426
427   fun_proto = cResType <+> pprCconv <+> ptext c_nm <>
428               parens (hsep (punctuate comma (zipWith (<+>) cParamTypes proto_args)))
429
430   c_bits =
431     externDecl $$
432     fun_proto  $$
433     vcat 
434      [ lbrace
435      ,   text "SchedulerStatus rc;"
436      ,   declareResult
437           -- create the application + perform it.
438      ,   text "rc=rts_evalIO" <> 
439                   parens (foldl appArg (text "(StgClosure*)&" <> h_nm) (zip args c_args) <> comma <> text "&ret") <> semi
440      ,   text "rts_checkSchedStatus" <> parens (doubleQuotes (ptext c_nm)
441                                                 <> comma <> text "rc") <> semi
442      ,   text "return" <> return_what <> semi
443      , rbrace
444      ]
445
446   appArg acc (a,c_a) =
447      text "rts_apply" <> parens (acc <> comma <> mkHObj a <> parens c_a)
448
449   cParamTypes  = map showStgType real_args
450
451   res_ty_is_unit = res_ty == unitTy
452
453   cResType | res_ty_is_unit = text "void"
454            | otherwise      = showStgType res_ty
455
456   pprCconv = case cc of
457                 CCallConv   -> empty
458                 StdCallConv -> ppr cc
459      
460   declareResult  = text "HaskellObj ret;"
461
462   externDecl     = mkExtern (text "HaskellObj") h_nm
463
464   mkExtern ty nm = text "extern" <+> ty <+> nm <> semi
465
466   return_what | res_ty_is_unit = empty
467               | otherwise      = parens (unpackHObj res_ty <> parens (text "ret"))
468
469   c_args = mkCArgNames 0 args
470
471   {-
472    If we're generating an entry point for a 'foreign export ccall dynamic',
473    then we receive the return address of the C function that wants to
474    invoke a Haskell function as any other C function, as second arg.
475    This arg is unused within the body of the generated C stub, but
476    needed by the Adjustor.c code to get the stack cleanup right.
477   -}
478   (proto_args, real_args)
479     = case cc of
480         CCallConv | isDyn -> ( text "a0" : text "a_" : mkCArgNames 1 (tail args)
481                              , head args : addrTy : tail args)
482         other             -> (mkCArgNames 0 args, args)
483
484 mkCArgNames :: Int -> [a] -> [SDoc]
485 mkCArgNames n as = zipWith (\ _ n -> text ('a':show n)) as [n..] 
486
487 mkHObj :: Type -> SDoc
488 mkHObj t = text "rts_mk" <> text (showFFIType t)
489
490 unpackHObj :: Type -> SDoc
491 unpackHObj t = text "rts_get" <> text (showFFIType t)
492
493 showStgType :: Type -> SDoc
494 showStgType t = text "Hs" <> text (showFFIType t)
495
496 showFFIType :: Type -> String
497 showFFIType t = getOccString (getName tc)
498  where
499   tc = case splitTyConApp_maybe (repType t) of
500             Just (tc,_) -> tc
501             Nothing     -> pprPanic "showFFIType" (ppr t)
502 \end{code}