c5e90f390b3816e772761debdf9f9c4cb9cac3f8
[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, boxResult, unboxArg, wrapUnboxedValue        )
16 import DsMonad
17 import DsUtils
18
19 import HsSyn            ( ExtName(..), ForeignDecl(..), isDynamic, ForKind(..) )
20 import CallConv
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, mkUserId )
26 import Const            ( Literal(..) )
27 import Name             ( mkGlobalName, nameModule, nameOccName, getOccString, 
28                           mkForeignExportOcc,
29                           NamedThing(..), Provenance(..), ExportFlag(..)
30                         )
31 import PrelVals         ( realWorldPrimId )
32 import PrelInfo         ( deRefStablePtr_NAME, bindIO_NAME, makeStablePtr_NAME )
33 import Type             ( splitAlgTyConApp_maybe, 
34                           splitTyConApp_maybe, splitFunTys, splitForAllTys,
35                           Type, mkFunTys, mkForAllTys, mkTyConApp,
36                           mkTyVarTy, mkFunTy, splitAppTy
37                         )
38 import PrimOp           ( PrimOp(..) )
39 import Var              ( TyVar )
40 import TysPrim          ( realWorldStatePrimTy, addrPrimTy )
41 import TysWiredIn       ( unitTyCon, addrTy, stablePtrTyCon,
42                           unboxedTupleCon, addrDataCon
43                         )
44 import Unique
45 import Outputable
46 \end{code}
47
48 Desugaring of @foreign@ declarations is naturally split up into
49 parts, an @import@ and an @export@  part. A @foreign import@ 
50 declaration 
51
52   foreign import cc nm f :: prim_args -> IO prim_res
53
54 is the same as
55
56   f :: prim_args -> IO prim_res
57   f a1 ... an = _ccall_ nm cc a1 ... an
58
59 so we reuse the desugaring code in @DsCCall@ to deal with these.
60
61 \begin{code}
62 dsForeigns :: [TypecheckedForeignDecl] 
63            -> DsM ( [CoreBind]        -- desugared foreign imports
64                   , [CoreBind]        -- helper functions for foreign exports
65                   , SDoc              -- Header file prototypes for "foreign exported" functions.
66                   , SDoc              -- C stubs to use when calling "foreign exported" funs.
67                   )
68 dsForeigns fos = foldlDs combine ([],[],empty,empty) fos
69  where
70   combine (acc_fi, acc_fe, acc_h, acc_c) fo@(ForeignDecl i imp_exp _ ext_nm cconv _) 
71     | isForeignImport =   -- foreign import (dynamic)?
72         dsFImport i (idType i) uns ext_nm cconv  `thenDs` \ b -> 
73         returnDs (b:acc_fi, acc_fe, acc_h, acc_c)
74     | isForeignLabel = 
75         dsFLabel i ext_nm `thenDs` \ b -> 
76         returnDs (b:acc_fi, acc_fe, acc_h, acc_c)
77     | isDynamic ext_nm =
78         dsFExportDynamic i (idType i) ext_nm cconv  `thenDs` \ (fi,fe,h,c) -> 
79         returnDs (fi:acc_fi, fe:acc_fe, h $$ acc_h, c $$ acc_c)
80
81     | otherwise        =  -- foreign export
82         dsFExport i (idType i) ext_nm cconv False   `thenDs` \ (fe,h,c) ->
83         returnDs (acc_fi, fe:acc_fe, h $$ acc_h, c $$ acc_c)
84    where
85     isForeignImport = 
86         case imp_exp of
87           FoImport _ -> True
88           _          -> False
89
90     isForeignLabel = 
91         case imp_exp of
92           FoLabel -> True
93           _       -> False
94
95     (FoImport uns)   = imp_exp
96
97 \end{code}
98
99 Desugaring foreign imports is just the matter of creating a binding
100 that on its RHS unboxes its arguments, performs the external call
101 (using the CCallOp primop), before boxing the result up and returning it.
102
103 \begin{code}
104 dsFImport :: Id
105           -> Type               -- Type of foreign import.
106           -> Bool               -- True <=> might cause Haskell GC
107           -> ExtName
108           -> CallConv
109           -> DsM CoreBind
110 dsFImport nm ty may_not_gc ext_name cconv =
111     newSysLocalDs realWorldStatePrimTy  `thenDs` \ old_s ->
112     splitForeignTyDs ty                 `thenDs` \ (tvs, args, mbIoDataCon, io_res_ty)  ->
113     let
114          the_state_arg
115            | is_io_action = old_s
116            | otherwise    = realWorldPrimId
117
118          arg_exprs = map (Var) args
119
120          is_io_action =
121             case mbIoDataCon of
122               Nothing -> False
123               _       -> True
124     in
125     mapAndUnzipDs unboxArg arg_exprs    `thenDs` \ (unboxed_args, arg_wrappers) ->
126     (if not is_io_action then
127        newSysLocalDs realWorldStatePrimTy `thenDs` \ state_tok ->
128        wrapUnboxedValue io_res_ty         `thenDs` \ (ccall_result_ty, v, res_v) ->
129        returnDs ( ccall_result_ty
130                 , \ prim_app -> Case prim_app  (mkWildId ccall_result_ty)
131                                     [(DataCon (unboxedTupleCon 2), [state_tok, v], res_v)])
132      else
133        boxResult io_res_ty)                     `thenDs` \ (final_result_ty, res_wrapper) ->
134     (case ext_name of
135        Dynamic       -> getUniqueDs `thenDs` \ u -> 
136                         returnDs (Right u)
137        ExtName fs _  -> returnDs (Left fs))     `thenDs` \ label ->
138     let
139         val_args   = Var the_state_arg : unboxed_args
140         final_args = Type inst_ty : val_args
141
142         -- A CCallOp has type (forall a. a), so we must instantiate
143         -- it at the full type, including the state argument
144         inst_ty = mkFunTys (map coreExprType val_args) final_result_ty
145
146         the_ccall_op = CCallOp label False (not may_not_gc) cconv
147
148         the_prim_app = mkPrimApp the_ccall_op (final_args :: [CoreArg])
149
150         body     = foldr ($) (res_wrapper the_prim_app) arg_wrappers
151
152         the_body 
153           | not is_io_action = body
154           | otherwise        = Lam old_s body
155     in
156     newSysLocalDs (coreExprType the_body) `thenDs` \ ds ->
157     let
158       io_app = 
159         case mbIoDataCon of
160           Nothing -> Var ds
161           Just ioDataCon ->
162                mkApps (Var (dataConId ioDataCon)) 
163                       [Type io_res_ty, Var ds]
164
165       fo_rhs = mkLams (tvs ++ args)
166                       (Let (NonRec ds (the_body::CoreExpr)) io_app)
167     in
168     returnDs (NonRec nm fo_rhs)
169 \end{code}
170
171 Given the type of a foreign import declaration, split it up into
172 its constituent parts.
173
174 \begin{code}
175 splitForeignTyDs :: Type -> DsM ([TyVar], [Id], Maybe DataCon, Type)
176 splitForeignTyDs ty = 
177     newSysLocalsDs arg_tys  `thenDs` \ ds_args ->
178     case splitAlgTyConApp_maybe res_ty of
179        Just (_,(io_res_ty:_),(ioCon:_)) ->   -- .... -> IO t
180              returnDs (tvs, ds_args, Just ioCon, io_res_ty)
181        _   ->                                -- .... -> t
182              returnDs (tvs, ds_args, Nothing, res_ty)
183   where
184    (arg_tys, res_ty)   = splitFunTys sans_foralls
185    (tvs, sans_foralls) = splitForAllTys ty
186
187 \end{code}
188
189 foreign labels 
190
191 \begin{code}
192 dsFLabel :: Id -> ExtName -> DsM CoreBind
193 dsFLabel nm ext_name = returnDs (NonRec nm fo_rhs)
194   where
195    fo_rhs = mkConApp addrDataCon [mkLit (MachLitLit enm addrPrimTy)]
196    enm    =
197     case ext_name of
198       ExtName f _ -> f
199       Dynamic     -> panic "dsFLabel: Dynamic - shouldn't ever happen."
200
201 \end{code}
202
203 The function that does most of the work for 'foreign export' declarations.
204 (see below for the boilerplate code a 'foreign export' declaration expands
205  into.)
206
207 For each 'foreign export foo' in a module M we generate:
208
209 * a C function 'foo', which calls
210 * a Haskell stub 'M.$ffoo', which calls
211
212 the user-written Haskell function 'M.foo'.
213
214 \begin{code}
215 dsFExport :: Id
216           -> Type               -- Type of foreign export.
217           -> ExtName
218           -> CallConv
219           -> Bool               -- True => invoke IO action that's hanging off 
220                                 -- the first argument's stable pointer
221           -> DsM ( CoreBind
222                  , SDoc
223                  , SDoc
224                  )
225 dsFExport i ty ext_name cconv isDyn =
226      getUniqueDs                                        `thenDs` \ uniq ->
227      getSrcLocDs                                        `thenDs` \ src_loc ->
228      let
229         f_helper_glob = mkUserId helper_name helper_ty
230                       where
231                         name        = idName i
232                         mod         = nameModule name
233                         occ         = mkForeignExportOcc (nameOccName name)
234                         prov        = LocalDef src_loc Exported
235                         helper_name = mkGlobalName uniq mod occ prov
236      in
237      newSysLocalsDs fe_arg_tys                          `thenDs` \ fe_args ->
238      (if isDyn then 
239         newSysLocalDs stbl_ptr_ty                       `thenDs` \ stbl_ptr ->
240         newSysLocalDs stbl_ptr_to_ty                    `thenDs` \ stbl_value ->
241         dsLookupGlobalValue deRefStablePtr_NAME         `thenDs` \ deRefStablePtrId ->
242         let
243          the_deref_app = mkApps (Var deRefStablePtrId)
244                                 [ Type stbl_ptr_to_ty, Var stbl_ptr ]
245         in
246         newSysLocalDs (coreExprType the_deref_app)       `thenDs` \ x_deref_app ->
247         dsLookupGlobalValue bindIO_NAME                  `thenDs` \ bindIOId ->
248         newSysLocalDs (mkFunTy stbl_ptr_to_ty 
249                                (mkTyConApp ioTyCon [res_ty])) `thenDs` \ x_cont ->
250         let
251          stbl_app      = \ cont -> 
252                 bindNonRec x_cont   (mkLams [stbl_value] cont) $
253                 bindNonRec x_deref_app the_deref_app  
254                            (mkApps (Var bindIOId)
255                                      [ Type stbl_ptr_to_ty
256                                      , Type res_ty
257                                      , Var x_deref_app
258                                      , Var x_cont])
259         in
260         returnDs (stbl_value, stbl_app, stbl_ptr)
261       else
262         returnDs (i, 
263                   \ body -> body,
264                   panic "stbl_ptr"  -- should never be touched.
265                   ))                                    `thenDs` \ (i, getFun_wrapper, stbl_ptr) ->
266      let
267       wrapper_args
268        | isDyn      = stbl_ptr:fe_args
269        | otherwise  = fe_args
270
271       wrapper_arg_tys
272        | isDyn      = stbl_ptr_ty:helper_arg_tys
273        | otherwise  = helper_arg_tys
274
275       the_app  = 
276          getFun_wrapper $
277          mkApps (Var i) (map (Type . mkTyVarTy) tvs ++ map Var fe_args)
278      in
279      getModuleAndGroupDs                `thenDs` \ (mod,_) -> 
280      getUniqueDs                        `thenDs` \ uniq ->
281      let
282       the_body = mkLams (tvs ++ wrapper_args) the_app
283
284       c_nm =
285         case ext_name of
286           ExtName fs _ -> fs
287           Dynamic      -> panic "dsFExport: Dynamic - shouldn't ever happen."
288
289       (h_stub, c_stub) = fexportEntry c_nm f_helper_glob wrapper_arg_tys the_result_ty cconv isDyn
290      in
291      returnDs (NonRec f_helper_glob the_body, h_stub, c_stub)
292
293   where
294
295    (tvs,sans_foralls)                   = splitForAllTys ty
296    (fe_arg_tys', io_res)                = splitFunTys sans_foralls
297
298
299    Just (ioTyCon, [res_ty])             = splitTyConApp_maybe io_res
300
301    (_, stbl_ptr_ty')                    = splitForAllTys stbl_ptr_ty
302    (_, stbl_ptr_to_ty)                  = splitAppTy stbl_ptr_ty'
303
304    fe_arg_tys
305      | isDyn        = tail fe_arg_tys'
306      | otherwise    = fe_arg_tys'
307
308    (stbl_ptr_ty, helper_arg_tys) = 
309      case fe_arg_tys' of
310        (x:xs) | isDyn -> (x,xs)
311        ls             -> (error "stbl_ptr_ty", ls)
312
313    helper_ty      =  
314         mkForAllTys tvs $
315         mkFunTys arg_tys io_res
316         where
317           arg_tys
318            | isDyn      = stbl_ptr_ty : helper_arg_tys
319            | otherwise  = helper_arg_tys
320
321    the_result_ty =
322      case splitTyConApp_maybe io_res of
323        Just (_,[res_ty]) ->
324          case splitTyConApp_maybe res_ty of
325            Just (tc,_) | getUnique tc /= getUnique unitTyCon -> Just res_ty
326            _                                                 -> Nothing
327        _                 -> Nothing
328    
329 \end{code}
330
331 "foreign export dynamic" lets you dress up Haskell IO actions
332 of some fixed type behind an externally callable interface (i.e.,
333 as a C function pointer). Useful for callbacks and stuff.
334
335 \begin{verbatim}
336 foreign export stdcall f :: (Addr -> Int -> IO Int) -> IO Addr
337
338 -- Haskell-visible constructor, which is generated from the
339 -- above:
340
341 f :: (Addr -> Int -> IO Int) -> IO Addr
342 f cback = IO ( \ s1# ->
343   case makeStablePtr# cback s1# of { StateAndStablePtr# s2# sp# ->
344   case _ccall_ "mkAdjustor" sp# ``f_helper'' s2# of
345     StateAndAddr# s3# a# ->
346     case addr2Int# a# of
347       0# -> IOfail s# err
348       _  -> 
349          let
350           a :: Addr
351           a = A# a#
352          in
353          IOok s3# a)
354
355 foreign export "f_helper" f_helper :: StablePtr (Addr -> Int -> IO Int) -> Addr -> Int -> IO Int
356 -- `special' foreign export that invokes the closure pointed to by the
357 -- first argument.
358 \end{verbatim}
359
360 \begin{code}
361 dsFExportDynamic :: Id
362                  -> Type                -- Type of foreign export.
363                  -> ExtName
364                  -> CallConv
365                  -> DsM (CoreBind, CoreBind, SDoc, SDoc)
366 dsFExportDynamic i ty ext_name cconv =
367      newSysLocalDs ty                                    `thenDs` \ fe_id ->
368      let 
369         -- hack: need to get at the name of the C stub we're about to generate.
370        fe_nm       = toCName fe_id
371        fe_ext_name = ExtName (_PK_ fe_nm) Nothing
372      in
373      dsFExport  i export_ty fe_ext_name cconv True `thenDs` \ (fe@(NonRec fe_helper fe_expr), h_code, c_code) ->
374      newSysLocalDs arg_ty                          `thenDs` \ cback ->
375      dsLookupGlobalValue makeStablePtr_NAME        `thenDs` \ makeStablePtrId ->
376      let
377         mk_stbl_ptr_app    = mkApps (Var makeStablePtrId) [ Type arg_ty, Var cback ]
378         mk_stbl_ptr_app_ty = coreExprType mk_stbl_ptr_app
379      in
380      newSysLocalDs mk_stbl_ptr_app_ty                   `thenDs` \ x_mk_stbl_ptr_app ->
381      dsLookupGlobalValue bindIO_NAME                    `thenDs` \ bindIOId ->
382      newSysLocalDs (mkTyConApp stablePtrTyCon [arg_ty]) `thenDs` \ stbl_value ->
383      let
384       stbl_app      = \ x_cont cont ret_ty -> 
385         bindNonRec x_cont            cont            $
386         bindNonRec x_mk_stbl_ptr_app mk_stbl_ptr_app $
387                    (mkApps (Var bindIOId)
388                            [ Type (mkTyConApp stablePtrTyCon [arg_ty])
389                            , Type ret_ty
390                            , Var x_mk_stbl_ptr_app
391                            , Var x_cont
392                            ])
393
394        {-
395         The arguments to the external function which will
396         create a little bit of (template) code on the fly
397         for allowing the (stable pointed) Haskell closure
398         to be entered using an external calling convention
399         (stdcall, ccall).
400        -}
401       adj_args      = [ mkLit (mkMachInt (fromInt (callConvToInt cconv)))
402                       , Var stbl_value
403                       , mkLit (MachLitLit (_PK_ fe_nm) addrPrimTy)
404                       ]
405         -- name of external entry point providing these services.
406         -- (probably in the RTS.) 
407       adjustor      = SLIT("createAdjustor")
408      in
409      dsCCall adjustor adj_args False False addrTy `thenDs` \ ccall_adj ->
410      let ccall_adj_ty = coreExprType ccall_adj
411      in
412      newSysLocalDs ccall_adj_ty                   `thenDs` \ x_ccall_adj ->
413      let ccall_io_adj = 
414             mkLams [stbl_value]              $
415             bindNonRec x_ccall_adj ccall_adj $
416             Note (Coerce (mkTyConApp ioTyCon [res_ty]) ccall_adj_ty)
417                  (Var x_ccall_adj)
418      in
419      newSysLocalDs (coreExprType ccall_io_adj)    `thenDs` \ x_ccall_io_adj ->
420      let io_app = mkLams tvs     $
421                   mkLams [cback] $
422                   stbl_app x_ccall_io_adj ccall_io_adj addrTy
423      in
424      returnDs (NonRec i io_app, fe, h_code, c_code)
425
426  where
427   (tvs,sans_foralls)               = splitForAllTys ty
428   ([arg_ty], io_res)               = splitFunTys sans_foralls
429
430   Just (ioTyCon, [res_ty])         = splitTyConApp_maybe io_res
431
432   export_ty                        = mkFunTy (mkTyConApp stablePtrTyCon [arg_ty]) arg_ty
433
434 toCName :: Id -> String
435 toCName i = showSDoc (pprCode CStyle (ppr (idName i)))
436
437 \end{code}
438
439 %*
440 %
441 \subsection{Generating @foreign export@ stubs}
442 %
443 %*
444
445 For each @foreign export@ function, a C stub function is generated.
446 The C stub constructs the application of the exported Haskell function 
447 using the hugs/ghc rts invocation API.
448
449 \begin{code}
450 fexportEntry :: FAST_STRING 
451              -> Id 
452              -> [Type] 
453              -> Maybe Type 
454              -> CallConv 
455              -> Bool
456              -> (SDoc, SDoc)
457 fexportEntry c_nm helper args res cc isDyn = (header_bits, c_bits)
458  where
459    -- name of the (Haskell) helper function generated by the desugarer.
460   h_nm      = ppr helper <> text "_closure"
461    -- prototype for the exported function.
462   header_bits = ptext SLIT("extern") <+> fun_proto <> semi
463
464   fun_proto = cResType <+> pprCconv <+> ptext c_nm <>
465               parens (hsep (punctuate comma (zipWith (<+>) cParamTypes proto_args)))
466
467   c_bits =
468     externDecl $$
469     fun_proto  $$
470     vcat 
471      [ lbrace
472      ,   text "SchedulerStatus rc;"
473      ,   declareResult
474           -- create the application + perform it.
475      ,   text "rc=rts_evalIO" <> 
476                   parens (foldl appArg (text "(StgClosure*)&" <> h_nm) (zip args c_args) <> comma <> text "&ret") <> semi
477      ,   returnResult
478      , rbrace
479      ]
480
481   appArg acc (a,c_a) =
482      text "rts_apply" <> parens (acc <> comma <> mkHObj a <> parens c_a)
483
484   cParamTypes  = map showStgType real_args
485
486   cResType = 
487    case res of
488      Nothing -> text "void"
489      Just t  -> showStgType t
490
491   pprCconv
492    | cc == cCallConv = empty
493    | otherwise       = pprCallConv cc
494      
495   declareResult  = text "HaskellObj ret;"
496
497   externDecl     = mkExtern (text "HaskellObj") h_nm
498
499   mkExtern ty nm = text "extern" <+> ty <+> nm <> semi
500
501   returnResult = 
502     text "rts_checkSchedStatus" <> 
503     parens (doubleQuotes (ptext c_nm) <> comma <> text "rc") <> semi $$
504     (case res of
505       Nothing -> text "return"
506       Just _  -> text "return" <> parens (res_name)) <> semi
507
508   res_name = 
509     case res of
510       Nothing -> empty
511       Just t  -> unpackHObj t <> parens (text "ret")
512
513   c_args = mkCArgNames 0 args
514
515   {-
516    If we're generating an entry point for a 'foreign export ccall dynamic',
517    then we receive the return address of the C function that wants to
518    invoke a Haskell function as any other C function, as second arg.
519    This arg is unused within the body of the generated C stub, but
520    needed by the Adjustor.c code to get the stack cleanup right.
521   -}
522   (proto_args, real_args)
523     | cc == cCallConv && isDyn = ( text "a0" : text "a_" : mkCArgNames 1 (tail args)
524                                 , head args : addrTy : tail args)
525     | otherwise = (mkCArgNames 0 args, args)
526
527   mkCArgNames n as = zipWith (\ _ n -> text ('a':show n)) as [n..] 
528
529 mkHObj :: Type -> SDoc
530 mkHObj t = text "rts_mk" <> showFFIType t
531
532 unpackHObj :: Type -> SDoc
533 unpackHObj t = text "rts_get" <> showFFIType t
534
535 showStgType :: Type -> SDoc
536 showStgType t = text "Stg" <> showFFIType t
537
538 showFFIType :: Type -> SDoc
539 showFFIType t = text (getOccString (getName tc))
540  where
541   tc = case splitTyConApp_maybe t of
542             Just (tc,_) -> tc
543             Nothing     -> pprPanic "showFFIType" (ppr t)
544 \end{code}