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