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