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