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