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