[project @ 2003-02-20 13:01:20 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, mkFCall, boxResult, unboxArg, resultWrapper )
16 import DsMonad
17
18 import HsSyn            ( ForeignDecl(..), ForeignExport(..),
19                           ForeignImport(..), CImportSpec(..) )
20 import TcHsSyn          ( TypecheckedForeignDecl )
21 import CoreUtils        ( exprType, mkInlineMe )
22 import Id               ( Id, idType, idName, mkSysLocal, setInlinePragma )
23 import Literal          ( Literal(..) )
24 import Module           ( moduleString )
25 import Name             ( getOccString, NamedThing(..) )
26 import OccName          ( encodeFS )
27 import Type             ( repType, eqType )
28 import TcType           ( Type, mkFunTys, mkForAllTys, mkTyConApp,
29                           mkFunTy, tcSplitTyConApp_maybe, 
30                           tcSplitForAllTys, tcSplitFunTys, tcTyConAppArgs,
31                         )
32
33 import HscTypes         ( ForeignStubs(..) )
34 import ForeignCall      ( ForeignCall(..), CCallSpec(..), 
35                           Safety(..), playSafe,
36                           CExportSpec(..),
37                           CCallConv(..), ccallConvToInt,
38                           ccallConvAttribute
39                         )
40 import CStrings         ( CLabelString )
41 import TysWiredIn       ( unitTy, stablePtrTyCon )
42 import TysPrim          ( addrPrimTy )
43 import PrelNames        ( hasKey, ioTyConKey, newStablePtrName, bindIOName )
44 import BasicTypes       ( Activation( NeverActive ) )
45 import Outputable
46 import Maybe            ( fromJust )
47 import FastString
48 \end{code}
49
50 Desugaring of @foreign@ declarations is naturally split up into
51 parts, an @import@ and an @export@  part. A @foreign import@ 
52 declaration
53 \begin{verbatim}
54   foreign import cc nm f :: prim_args -> IO prim_res
55 \end{verbatim}
56 is the same as
57 \begin{verbatim}
58   f :: prim_args -> IO prim_res
59   f a1 ... an = _ccall_ nm cc a1 ... an
60 \end{verbatim}
61 so we reuse the desugaring code in @DsCCall@ to deal with these.
62
63 \begin{code}
64 type Binding = (Id, CoreExpr)   -- No rec/nonrec structure;
65                                 -- the occurrence analyser will sort it all out
66
67 dsForeigns :: [TypecheckedForeignDecl] 
68            -> DsM (ForeignStubs, [Binding])
69 dsForeigns [] 
70   = returnDs (NoStubs, [])
71 dsForeigns fos
72   = foldlDs combine (ForeignStubs empty empty [] [], []) fos
73  where
74   combine (ForeignStubs acc_h acc_c acc_hdrs acc_feb, acc_f) 
75           (ForeignImport id _ spec depr loc)
76     = dsFImport id spec            `thenDs` \(bs, h, c, hd) -> 
77       warnDepr depr loc                            `thenDs` \_              ->
78       returnDs (ForeignStubs (h $$ acc_h) (c $$ acc_c) (hd ++ acc_hdrs) acc_feb, 
79                 bs ++ acc_f)
80
81   combine (ForeignStubs acc_h acc_c acc_hdrs acc_feb, acc_f) 
82           (ForeignExport id _ (CExport (CExportStatic ext_nm cconv)) depr loc)
83     = dsFExport id (idType id) 
84                 ext_nm cconv False                 `thenDs` \(h, c) ->
85       warnDepr depr loc                            `thenDs` \_              ->
86       returnDs (ForeignStubs (h $$ acc_h) (c $$ acc_c) acc_hdrs (id:acc_feb), 
87                 acc_f)
88
89   warnDepr False _   = returnDs ()
90   warnDepr True  loc = dsWarn (loc, msg)
91    where
92     msg = ptext SLIT("foreign declaration uses deprecated non-standard syntax")
93 \end{code}
94
95
96 %************************************************************************
97 %*                                                                      *
98 \subsection{Foreign import}
99 %*                                                                      *
100 %************************************************************************
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 However, we create a worker/wrapper pair, thus:
107
108         foreign import f :: Int -> IO Int
109 ==>
110         f x = IO ( \s -> case x of { I# x# ->
111                          case fw s x# of { (# s1, y# #) ->
112                          (# s1, I# y# #)}})
113
114         fw s x# = ccall f s x#
115
116 The strictness/CPR analyser won't do this automatically because it doesn't look
117 inside returned tuples; but inlining this wrapper is a Really Good Idea 
118 because it exposes the boxing to the call site.
119
120 \begin{code}
121 dsFImport :: Id
122           -> ForeignImport
123           -> DsM ([Binding], SDoc, SDoc, [FastString])
124 dsFImport id (CImport cconv safety header lib spec)
125   = dsCImport id spec cconv safety no_hdrs        `thenDs` \(ids, h, c) ->
126     returnDs (ids, h, c, if no_hdrs then [] else [header])
127   where
128     no_hdrs = nullFastString header
129
130   -- FIXME: the `lib' field is needed for .NET ILX generation when invoking
131   --        routines that are external to the .NET runtime, but GHC doesn't
132   --        support such calls yet; if `nullFastString lib', the value was not given
133 dsFImport id (DNImport spec)
134   = dsFCall id (DNCall spec) True {- No headers -} `thenDs` \(ids, h, c) ->
135     returnDs (ids, h, c, [])
136
137 dsCImport :: Id
138           -> CImportSpec
139           -> CCallConv
140           -> Safety
141           -> Bool       -- True <=> no headers in the f.i decl
142           -> DsM ([Binding], SDoc, SDoc)
143 dsCImport id (CLabel cid) _ _ no_hdrs
144  = ASSERT(fromJust resTy `eqType` addrPrimTy)    -- typechecker ensures this
145    returnDs ([(setImpInline no_hdrs id, rhs)], empty, empty)
146  where
147    (resTy, foRhs) = resultWrapper (idType id)
148    rhs            = foRhs (mkLit (MachLabel cid))
149 dsCImport id (CFunction target) cconv safety no_hdrs
150   = dsFCall id (CCall (CCallSpec target cconv safety)) no_hdrs
151 dsCImport id CWrapper cconv _ _
152   = dsFExportDynamic id cconv
153
154 setImpInline :: Bool    -- True <=> No #include headers 
155                         -- in the foreign import declaration
156              -> Id -> Id
157 -- If there is a #include header in the foreign import
158 -- we make the worker non-inlinable, because we currently
159 -- don't keep the #include stuff in the CCallId, and hence
160 -- it won't be visible in the importing module, which can be
161 -- fatal. 
162 -- (The #include stuff is just collected from the foreign import
163 --  decls in a module.)
164 -- If you want to do cross-module inlining of the c-calls themselves,
165 -- put the #include stuff in the package spec, not the foreign 
166 -- import decl.
167 setImpInline True  id = id
168 setImpInline False id = id `setInlinePragma` NeverActive
169 \end{code}
170
171
172 %************************************************************************
173 %*                                                                      *
174 \subsection{Foreign calls}
175 %*                                                                      *
176 %************************************************************************
177
178 \begin{code}
179 dsFCall fn_id fcall no_hdrs
180   = let
181         ty                   = idType fn_id
182         (tvs, fun_ty)        = tcSplitForAllTys ty
183         (arg_tys, io_res_ty) = tcSplitFunTys fun_ty
184                 -- Must use tcSplit* functions because we want to 
185                 -- see that (IO t) in the corner
186     in
187     newSysLocalsDs arg_tys                      `thenDs` \ args ->
188     mapAndUnzipDs unboxArg (map Var args)       `thenDs` \ (val_args, arg_wrappers) ->
189
190     let
191         work_arg_ids  = [v | Var v <- val_args] -- All guaranteed to be vars
192
193         -- These are the ids we pass to boxResult, which are used to decide
194         -- whether to touch# an argument after the call (used to keep
195         -- ForeignObj#s live across a 'safe' foreign import).
196         maybe_arg_ids | unsafe_call fcall = work_arg_ids
197                       | otherwise         = []
198     in
199     boxResult maybe_arg_ids io_res_ty           `thenDs` \ (ccall_result_ty, res_wrapper) ->
200
201     getUniqueDs                                 `thenDs` \ ccall_uniq ->
202     getUniqueDs                                 `thenDs` \ work_uniq ->
203     let
204         -- Build the worker
205         worker_ty     = mkForAllTys tvs (mkFunTys (map idType work_arg_ids) ccall_result_ty)
206         the_ccall_app = mkFCall ccall_uniq fcall val_args ccall_result_ty
207         work_rhs      = mkLams tvs (mkLams work_arg_ids the_ccall_app)
208         work_id       = setImpInline no_hdrs $  -- See comments with setImpInline
209                         mkSysLocal (encodeFS FSLIT("$wccall")) work_uniq worker_ty
210
211         -- Build the wrapper
212         work_app     = mkApps (mkVarApps (Var work_id) tvs) val_args
213         wrapper_body = foldr ($) (res_wrapper work_app) arg_wrappers
214         wrap_rhs     = mkInlineMe (mkLams (tvs ++ args) wrapper_body)
215     in
216     returnDs ([(work_id, work_rhs), (fn_id, wrap_rhs)], empty, empty)
217
218 unsafe_call (CCall (CCallSpec _ _ safety)) = playSafe safety
219 unsafe_call (DNCall _)                     = False
220 \end{code}
221
222
223 %************************************************************************
224 %*                                                                      *
225 \subsection{Foreign export}
226 %*                                                                      *
227 %************************************************************************
228
229 The function that does most of the work for `@foreign export@' declarations.
230 (see below for the boilerplate code a `@foreign export@' declaration expands
231  into.)
232
233 For each `@foreign export foo@' in a module M we generate:
234 \begin{itemize}
235 \item a C function `@foo@', which calls
236 \item a Haskell stub `@M.$ffoo@', which calls
237 \end{itemize}
238 the user-written Haskell function `@M.foo@'.
239
240 \begin{code}
241 dsFExport :: Id                 -- Either the exported Id, 
242                                 -- or the foreign-export-dynamic constructor
243           -> Type               -- The type of the thing callable from C
244           -> CLabelString       -- The name to export to C land
245           -> CCallConv
246           -> Bool               -- True => foreign export dynamic
247                                 --         so invoke IO action that's hanging off 
248                                 --         the first argument's stable pointer
249           -> DsM ( SDoc         -- contents of Module_stub.h
250                  , SDoc         -- contents of Module_stub.c
251                  )
252
253 dsFExport fn_id ty ext_name cconv isDyn
254    = 
255      let
256         (tvs,sans_foralls)              = tcSplitForAllTys ty
257         (fe_arg_tys', orig_res_ty)      = tcSplitFunTys sans_foralls
258         -- We must use tcSplits here, because we want to see 
259         -- the (IO t) in the corner of the type!
260         fe_arg_tys | isDyn     = tail fe_arg_tys'
261                    | otherwise = fe_arg_tys'
262      in
263         -- Look at the result type of the exported function, orig_res_ty
264         -- If it's IO t, return         (t, True)
265         -- If it's plain t, return      (t, False)
266      (case tcSplitTyConApp_maybe orig_res_ty of
267         -- We must use tcSplit here so that we see the (IO t) in
268         -- the type.  [IO t is transparent to plain splitTyConApp.]
269
270         Just (ioTyCon, [res_ty])
271               -> ASSERT( ioTyCon `hasKey` ioTyConKey )
272                  -- The function already returns IO t
273                  returnDs (res_ty, True)
274
275         other -> -- The function returns t
276                  returnDs (orig_res_ty, False)
277      )
278                                         `thenDs` \ (res_ty,             -- t
279                                                     is_IO_res_ty) ->    -- Bool
280      let
281         (h_stub, c_stub) 
282            = mkFExportCBits ext_name 
283                             (if isDyn then Nothing else Just fn_id)
284                             fe_arg_tys res_ty is_IO_res_ty cconv
285      in
286      returnDs (h_stub, c_stub)
287 \end{code}
288
289 @foreign export dynamic@ lets you dress up Haskell IO actions
290 of some fixed type behind an externally callable interface (i.e.,
291 as a C function pointer). Useful for callbacks and stuff.
292
293 \begin{verbatim}
294 foreign export dynamic f :: (Addr -> Int -> IO Int) -> IO Addr
295
296 -- Haskell-visible constructor, which is generated from the above:
297 -- SUP: No check for NULL from createAdjustor anymore???
298
299 f :: (Addr -> Int -> IO Int) -> IO Addr
300 f cback =
301    bindIO (newStablePtr cback)
302           (\StablePtr sp# -> IO (\s1# ->
303               case _ccall_ createAdjustor cconv sp# ``f_helper'' s1# of
304                  (# s2#, a# #) -> (# s2#, A# a# #)))
305
306 foreign export "f_helper" f_helper :: StablePtr (Addr -> Int -> IO Int) -> Addr -> Int -> IO Int
307 -- `special' foreign export that invokes the closure pointed to by the
308 -- first argument.
309 \end{verbatim}
310
311 \begin{code}
312 dsFExportDynamic :: Id
313                  -> CCallConv
314                  -> DsM ([Binding], SDoc, SDoc)
315 dsFExportDynamic id cconv
316   =  newSysLocalDs ty                            `thenDs` \ fe_id ->
317      getModuleDs                                `thenDs` \ mod_name -> 
318      let 
319         -- hack: need to get at the name of the C stub we're about to generate.
320        fe_nm       = mkFastString (moduleString mod_name ++ "_" ++ toCName fe_id)
321      in
322      dsFExport id export_ty fe_nm cconv True    `thenDs` \ (h_code, c_code) ->
323      newSysLocalDs arg_ty                       `thenDs` \ cback ->
324      dsLookupGlobalId newStablePtrName  `thenDs` \ newStablePtrId ->
325      let
326         mk_stbl_ptr_app    = mkApps (Var newStablePtrId) [ Type arg_ty, Var cback ]
327      in
328      dsLookupGlobalId bindIOName                        `thenDs` \ bindIOId ->
329      newSysLocalDs (mkTyConApp stablePtrTyCon [arg_ty]) `thenDs` \ stbl_value ->
330      let
331       stbl_app cont ret_ty 
332         = mkApps (Var bindIOId)
333                  [ Type (mkTyConApp stablePtrTyCon [arg_ty])
334                  , Type ret_ty
335                  , mk_stbl_ptr_app
336                  , cont
337                  ]
338
339        {-
340         The arguments to the external function which will
341         create a little bit of (template) code on the fly
342         for allowing the (stable pointed) Haskell closure
343         to be entered using an external calling convention
344         (stdcall, ccall).
345        -}
346       adj_args      = [ mkIntLitInt (ccallConvToInt cconv)
347                       , Var stbl_value
348                       , mkLit (MachLabel fe_nm)
349                       ]
350         -- name of external entry point providing these services.
351         -- (probably in the RTS.) 
352       adjustor      = FSLIT("createAdjustor")
353      in
354      dsCCall adjustor adj_args PlayRisky False io_res_ty        `thenDs` \ ccall_adj ->
355         -- PlayRisky: the adjustor doesn't allocate in the Haskell heap or do a callback
356      let ccall_adj_ty = exprType ccall_adj
357          ccall_io_adj = mkLams [stbl_value]                  $
358                         Note (Coerce io_res_ty ccall_adj_ty)
359                              ccall_adj
360          io_app = mkLams tvs     $
361                   mkLams [cback] $
362                   stbl_app ccall_io_adj res_ty
363          fed = (id `setInlinePragma` NeverActive, io_app)
364                 -- Never inline the f.e.d. function, because the litlit
365                 -- might not be in scope in other modules.
366      in
367      returnDs ([fed], h_code, c_code)
368
369  where
370   ty                    = idType id
371   (tvs,sans_foralls)    = tcSplitForAllTys ty
372   ([arg_ty], io_res_ty) = tcSplitFunTys sans_foralls
373   [res_ty]              = tcTyConAppArgs io_res_ty
374         -- Must use tcSplit* to see the (IO t), which is a newtype
375   export_ty             = mkFunTy (mkTyConApp stablePtrTyCon [arg_ty]) arg_ty
376
377 toCName :: Id -> String
378 toCName i = showSDoc (pprCode CStyle (ppr (idName i)))
379 \end{code}
380
381 %*
382 %
383 \subsection{Generating @foreign export@ stubs}
384 %
385 %*
386
387 For each @foreign export@ function, a C stub function is generated.
388 The C stub constructs the application of the exported Haskell function 
389 using the hugs/ghc rts invocation API.
390
391 \begin{code}
392 mkFExportCBits :: FastString
393                -> Maybe Id      -- Just==static, Nothing==dynamic
394                -> [Type] 
395                -> Type 
396                -> Bool          -- True <=> returns an IO type
397                -> CCallConv 
398                -> (SDoc, SDoc)
399 mkFExportCBits c_nm maybe_target arg_htys res_hty is_IO_res_ty cc 
400  = (header_bits, c_bits)
401  where
402   -- Create up types and names for the real args
403   arg_cnames, arg_ctys :: [SDoc]
404   arg_cnames = mkCArgNames 1 arg_htys
405   arg_ctys   = map showStgType arg_htys
406
407   -- and also for auxiliary ones; the stable ptr in the dynamic case, and
408   -- a slot for the dummy return address in the dynamic + ccall case
409   extra_cnames_and_ctys
410      = case maybe_target of
411           Nothing -> [(text "the_stableptr", text "StgStablePtr")]
412           other   -> []
413        ++
414        case (maybe_target, cc) of
415           (Nothing, CCallConv) -> [(text "original_return_addr", text "void*")]
416           other                -> []
417
418   all_cnames_and_ctys :: [(SDoc, SDoc)]
419   all_cnames_and_ctys 
420      = extra_cnames_and_ctys ++ zip arg_cnames arg_ctys
421
422   -- stuff to do with the return type of the C function
423   res_hty_is_unit = res_hty `eqType` unitTy     -- Look through any newtypes
424
425   cResType | res_hty_is_unit = text "void"
426            | otherwise       = showStgType res_hty
427
428   -- Now we can cook up the prototype for the exported function.
429   pprCconv = case cc of
430                 CCallConv   -> empty
431                 StdCallConv -> text (ccallConvAttribute cc)
432
433   header_bits = ptext SLIT("extern") <+> fun_proto <> semi
434
435   fun_proto = cResType <+> pprCconv <+> ftext c_nm <>
436               parens (hsep (punctuate comma (map (\(nm,ty) -> ty <+> nm) 
437                                                  all_cnames_and_ctys)))
438
439   -- the target which will form the root of what we ask rts_evalIO to run
440   the_cfun
441      = case maybe_target of
442           Nothing    -> text "(StgClosure*)deRefStablePtr(the_stableptr)"
443           Just hs_fn -> char '&' <> ppr hs_fn <> text "_closure"
444
445   -- the expression we give to rts_evalIO
446   expr_to_run
447      = foldl appArg the_cfun (zip arg_cnames arg_htys)
448        where
449           appArg acc (arg_cname, arg_hty) 
450              = text "rts_apply" 
451                <> parens (acc <> comma <> mkHObj arg_hty <> parens arg_cname)
452
453   -- various other bits for inside the fn
454   declareResult = text "HaskellObj ret;"
455   declareCResult | res_hty_is_unit = empty
456                  | otherwise       = cResType <+> text "cret;"
457
458   assignCResult | res_hty_is_unit = empty
459                 | otherwise       =
460                         text "cret=" <> unpackHObj res_hty <> parens (text "ret") <> semi
461
462   -- an extern decl for the fn being called
463   extern_decl
464      = case maybe_target of
465           Nothing -> empty
466           Just hs_fn -> text "extern StgClosure " <> ppr hs_fn <> text "_closure" <> semi
467
468   -- finally, the whole darn thing
469   c_bits =
470     space $$
471     extern_decl $$
472     fun_proto  $$
473     vcat 
474      [ lbrace
475      ,   text "SchedulerStatus rc;"
476      ,   declareResult
477      ,   declareCResult
478      ,   text "rts_lock();"
479           -- create the application + perform it.
480      ,   text "rc=rts_evalIO" <> parens (
481                 text "rts_apply" <> parens (
482                     text "(HaskellObj)"
483                  <> text (if is_IO_res_ty 
484                                 then "runIO_closure" 
485                                 else "runNonIO_closure")
486                  <> comma
487                  <> expr_to_run
488                 ) <+> comma
489                <> text "&ret"
490              ) <> semi
491      ,   text "rts_checkSchedStatus" <> parens (doubleQuotes (ftext c_nm)
492                                                 <> comma <> text "rc") <> semi
493      ,   assignCResult
494      ,   text "rts_unlock();"
495      ,   if res_hty_is_unit then empty
496             else text "return cret;"
497      , rbrace
498      ]
499
500
501 mkCArgNames :: Int -> [a] -> [SDoc]
502 mkCArgNames n as = zipWith (\ _ n -> text ('a':show n)) as [n..] 
503
504 mkHObj :: Type -> SDoc
505 mkHObj t = text "rts_mk" <> text (showFFIType t)
506
507 unpackHObj :: Type -> SDoc
508 unpackHObj t = text "rts_get" <> text (showFFIType t)
509
510 showStgType :: Type -> SDoc
511 showStgType t = text "Hs" <> text (showFFIType t)
512
513 showFFIType :: Type -> String
514 showFFIType t = getOccString (getName tc)
515  where
516   tc = case tcSplitTyConApp_maybe (repType t) of
517             Just (tc,_) -> tc
518             Nothing     -> pprPanic "showFFIType" (ppr t)
519 \end{code}