[project @ 2002-02-04 03:40:31 by chak]
[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, mkVanillaGlobal, mkSysLocal,
23                           setInlinePragma )
24 import IdInfo           ( vanillaIdInfo )
25 import Literal          ( Literal(..) )
26 import Module           ( Module, moduleUserString )
27 import Name             ( mkGlobalName, nameModule, nameOccName, getOccString, 
28                           mkForeignExportOcc, isLocalName,
29                           NamedThing(..),
30                         )
31 import Type             ( repType, eqType )
32 import TcType           ( Type, mkFunTys, mkForAllTys, mkTyConApp,
33                           mkFunTy, applyTy, 
34                           tcSplitForAllTys, tcSplitFunTys, tcTyConAppArgs,
35                           tcSplitTyConApp_maybe, tcSplitAppTy,
36                           tcFunResultTy
37                         )
38
39 import ForeignCall      ( ForeignCall(..), CCallSpec(..), 
40                           Safety(..), playSafe,
41                           CExportSpec(..),
42                           CCallConv(..), ccallConvToInt
43                         )
44 import CStrings         ( CLabelString )
45 import TysWiredIn       ( addrTy, unitTy, stablePtrTyCon )
46 import TysPrim          ( addrPrimTy )
47 import PrelNames        ( hasKey, ioTyConKey, deRefStablePtrName, newStablePtrName,
48                           bindIOName, returnIOName
49                         )
50 import BasicTypes       ( Activation( NeverActive ) )
51 import ErrUtils         ( addShortWarnLocLine )
52 import Outputable
53 import Maybe            ( fromJust )
54 \end{code}
55
56 Desugaring of @foreign@ declarations is naturally split up into
57 parts, an @import@ and an @export@  part. A @foreign import@ 
58 declaration
59 \begin{verbatim}
60   foreign import cc nm f :: prim_args -> IO prim_res
61 \end{verbatim}
62 is the same as
63 \begin{verbatim}
64   f :: prim_args -> IO prim_res
65   f a1 ... an = _ccall_ nm cc a1 ... an
66 \end{verbatim}
67 so we reuse the desugaring code in @DsCCall@ to deal with these.
68
69 \begin{code}
70 type Binding = (Id, CoreExpr)   -- No rec/nonrec structure;
71                                 -- the occurrence analyser will sort it all out
72
73 dsForeigns :: Module
74            -> [TypecheckedForeignDecl] 
75            -> DsM ( [Id]                -- Foreign-exported binders; 
76                                         -- we have to generate code to register these
77                   , [Binding]
78                   , SDoc              -- Header file prototypes for
79                                       -- "foreign exported" functions.
80                   , SDoc              -- C stubs to use when calling
81                                       -- "foreign exported" functions.
82                   , [FAST_STRING]     -- headers that need to be included
83                                       -- into C code generated for this module
84                   )
85 dsForeigns mod_name fos
86   = foldlDs combine ([], [], empty, empty, []) fos
87  where
88   combine (acc_feb, acc_f, acc_h, acc_c, acc_header) 
89           (ForeignImport id _ spec depr loc)
90     = dsFImport mod_name id spec                   `thenDs` \(bs, h, c, hd) -> 
91       warnDepr depr loc                            `thenDs` \_              ->
92       returnDs (acc_feb, bs ++ acc_f, h $$ acc_h, c $$ acc_c, hd ++ acc_header)
93
94   combine (acc_feb, acc_f, acc_h, acc_c, acc_header) 
95           (ForeignExport id _ (CExport (CExportStatic ext_nm cconv)) depr loc)
96     = dsFExport mod_name id (idType id) 
97                 ext_nm cconv False                 `thenDs` \(feb, b, h, c) ->
98       warnDepr depr loc                            `thenDs` \_              ->
99       returnDs (feb:acc_feb, b : acc_f, h $$ acc_h, c $$ acc_c, acc_header)
100
101   warnDepr False _   = returnDs ()
102   warnDepr True  loc = dsWarn (addShortWarnLocLine loc msg)
103    where
104     msg = ptext SLIT("foreign declaration uses deprecated non-standard syntax")
105 \end{code}
106
107
108 %************************************************************************
109 %*                                                                      *
110 \subsection{Foreign import}
111 %*                                                                      *
112 %************************************************************************
113
114 Desugaring foreign imports is just the matter of creating a binding
115 that on its RHS unboxes its arguments, performs the external call
116 (using the @CCallOp@ primop), before boxing the result up and returning it.
117
118 However, we create a worker/wrapper pair, thus:
119
120         foreign import f :: Int -> IO Int
121 ==>
122         f x = IO ( \s -> case x of { I# x# ->
123                          case fw s x# of { (# s1, y# #) ->
124                          (# s1, I# y# #)}})
125
126         fw s x# = ccall f s x#
127
128 The strictness/CPR analyser won't do this automatically because it doesn't look
129 inside returned tuples; but inlining this wrapper is a Really Good Idea 
130 because it exposes the boxing to the call site.
131
132 \begin{code}
133 dsFImport :: Module
134           -> Id
135           -> ForeignImport
136           -> DsM ([Binding], SDoc, SDoc, [FAST_STRING])
137 dsFImport modName id (CImport cconv safety header lib spec) = 
138   dsCImport modName id spec cconv safety          `thenDs` \(ids, h, c) ->
139   returnDs (ids, h, c, if _NULL_ header then [] else [header])
140   -- FIXME: the `lib' field is needed for .NET ILX generation when invoking
141   --        routines that are external to the .NET runtime, but GHC doesn't
142   --        support such calls yet; if `_NULL_ lib', the value was not given
143 dsFImport modName id (DNImport spec)                        = 
144   dsFCall modName id (DNCall spec)                `thenDs` \(ids, h, c) ->
145   returnDs (ids, h, c, [])
146
147 dsCImport :: Module
148           -> Id
149           -> CImportSpec
150           -> CCallConv
151           -> Safety
152           -> DsM ([Binding], SDoc, SDoc)
153 dsCImport modName id (CLabel cid)       _     _      =
154  ASSERT(fromJust res_ty `eqType` addrPrimTy)    -- typechecker ensures this
155  returnDs ([(id, rhs)], empty, empty)
156  where
157    (resTy, foRhs) = resultWrapper (idType id)
158    rhs            = foRhs (mkLit (MachLabel cid))
159 dsCImport modName id (CFunction target) cconv safety =
160   dsFCall modName id (CCall (CCallSpec target cconv safety))
161 dsCImport modName id CWrapper           cconv _      =
162   dsFExportDynamic modName id cconv
163 \end{code}
164
165
166 %************************************************************************
167 %*                                                                      *
168 \subsection{Foreign calls}
169 %*                                                                      *
170 %************************************************************************
171
172 \begin{code}
173 dsFCall mod_Name fn_id fcall
174   = let
175         ty                   = idType fn_id
176         (tvs, fun_ty)        = tcSplitForAllTys ty
177         (arg_tys, io_res_ty) = tcSplitFunTys fun_ty
178                 -- Must use tcSplit* functions because we want to 
179                 -- see that (IO t) in the corner
180     in
181     newSysLocalsDs arg_tys                      `thenDs` \ args ->
182     mapAndUnzipDs unboxArg (map Var args)       `thenDs` \ (val_args, arg_wrappers) ->
183
184     let
185         work_arg_ids  = [v | Var v <- val_args] -- All guaranteed to be vars
186
187         -- These are the ids we pass to boxResult, which are used to decide
188         -- whether to touch# an argument after the call (used to keep
189         -- ForeignObj#s live across a 'safe' foreign import).
190         maybe_arg_ids | unsafe_call fcall = work_arg_ids
191                       | otherwise         = []
192     in
193     boxResult maybe_arg_ids io_res_ty           `thenDs` \ (ccall_result_ty, res_wrapper) ->
194
195     getUniqueDs                                 `thenDs` \ ccall_uniq ->
196     getUniqueDs                                 `thenDs` \ work_uniq ->
197     let
198         -- Build the worker
199         worker_ty     = mkForAllTys tvs (mkFunTys (map idType work_arg_ids) ccall_result_ty)
200         the_ccall_app = mkFCall ccall_uniq fcall val_args ccall_result_ty
201         work_rhs      = mkLams tvs (mkLams work_arg_ids the_ccall_app)
202         work_id       = mkSysLocal SLIT("$wccall") work_uniq worker_ty
203
204         -- Build the wrapper
205         work_app     = mkApps (mkVarApps (Var work_id) tvs) val_args
206         wrapper_body = foldr ($) (res_wrapper work_app) arg_wrappers
207         wrap_rhs     = mkInlineMe (mkLams (tvs ++ args) wrapper_body)
208     in
209     returnDs ([(work_id, work_rhs), (fn_id, wrap_rhs)], empty, empty)
210
211 unsafe_call (CCall (CCallSpec _ _ safety)) = playSafe safety
212 unsafe_call (DNCall _)                     = False
213 \end{code}
214
215
216 %************************************************************************
217 %*                                                                      *
218 \subsection{Foreign export}
219 %*                                                                      *
220 %************************************************************************
221
222 The function that does most of the work for `@foreign export@' declarations.
223 (see below for the boilerplate code a `@foreign export@' declaration expands
224  into.)
225
226 For each `@foreign export foo@' in a module M we generate:
227 \begin{itemize}
228 \item a C function `@foo@', which calls
229 \item a Haskell stub `@M.$ffoo@', which calls
230 \end{itemize}
231 the user-written Haskell function `@M.foo@'.
232
233 \begin{code}
234 dsFExport :: Module
235           -> Id                 -- Either the exported Id, 
236                                 -- or the foreign-export-dynamic constructor
237           -> Type               -- The type of the thing callable from C
238           -> CLabelString       -- The name to export to C land
239           -> CCallConv
240           -> Bool               -- True => foreign export dynamic
241                                 --         so invoke IO action that's hanging off 
242                                 --         the first argument's stable pointer
243           -> DsM ( Id           -- The foreign-exported Id
244                  , Binding
245                  , SDoc
246                  , SDoc
247                  )
248 dsFExport mod_name fn_id ty ext_name cconv isDyn
249   =     -- BUILD THE returnIO WRAPPER, if necessary
250         -- Look at the result type of the exported function, orig_res_ty
251         -- If it's IO t, return         (\x.x,          IO t, t)
252         -- If it's plain t, return      (\x.returnIO x, IO t, t)
253      (case tcSplitTyConApp_maybe orig_res_ty of
254         -- We must use tcSplit here so that we see the (IO t) in
255         -- the type.  [IO t is transparent to plain splitTyConApp.]
256
257         Just (ioTyCon, [res_ty])
258               -> ASSERT( ioTyCon `hasKey` ioTyConKey )
259                         -- The function already returns IO t
260                  returnDs (\body -> body, orig_res_ty, res_ty)
261
262         other ->        -- The function returns t, so wrap the call in returnIO
263                  dsLookupGlobalValue returnIOName       `thenDs` \ retIOId ->
264                  returnDs (\body -> mkApps (Var retIOId) [Type orig_res_ty, body],
265                            tcFunResultTy (applyTy (idType retIOId) orig_res_ty), 
266                                 -- We don't have ioTyCon conveniently to hand
267                            orig_res_ty)
268
269      )          `thenDs` \ (return_io_wrapper,  -- Either identity or returnIO
270                             io_res_ty,          -- IO t
271                             res_ty) ->          -- t
272
273
274         -- BUILD THE deRefStablePtr WRAPPER, if necessary
275      (if isDyn then 
276         newSysLocalDs stbl_ptr_ty                       `thenDs` \ stbl_ptr ->
277         newSysLocalDs stbl_ptr_to_ty                    `thenDs` \ stbl_value ->
278         dsLookupGlobalValue deRefStablePtrName          `thenDs` \ deRefStablePtrId ->
279         dsLookupGlobalValue bindIOName                  `thenDs` \ bindIOId ->
280         let
281          the_deref_app = mkApps (Var deRefStablePtrId)
282                                 [ Type stbl_ptr_to_ty, Var stbl_ptr ]
283
284          stbl_app cont = mkApps (Var bindIOId)
285                                 [ Type stbl_ptr_to_ty
286                                 , Type res_ty
287                                 , the_deref_app
288                                 , mkLams [stbl_value] cont]
289         in
290         returnDs (stbl_value, stbl_app, stbl_ptr)
291       else
292         returnDs (fn_id, 
293                   \ body -> body,
294                   panic "stbl_ptr"  -- should never be touched.
295                   ))                    `thenDs` \ (i, getFun_wrapper, stbl_ptr) ->
296
297
298         -- BUILD THE HELPER
299      getModuleDs                        `thenDs` \ mod -> 
300      getUniqueDs                        `thenDs` \ uniq ->
301      getSrcLocDs                        `thenDs` \ src_loc ->
302      newSysLocalsDs fe_arg_tys          `thenDs` \ fe_args ->
303      let
304         wrapper_args | isDyn      = stbl_ptr:fe_args
305                      | otherwise  = fe_args
306
307         wrapper_arg_tys | isDyn      = stbl_ptr_ty:fe_arg_tys
308                         | otherwise  = fe_arg_tys
309
310         helper_ty =  mkForAllTys tvs $
311                      mkFunTys wrapper_arg_tys io_res_ty
312
313         f_helper_glob = mkVanillaGlobal helper_name helper_ty vanillaIdInfo
314                       where
315                         name                = idName fn_id
316                         mod     
317                          | isLocalName name = mod_name
318                          | otherwise        = nameModule name
319
320                         occ                 = mkForeignExportOcc (nameOccName name)
321                         helper_name         = mkGlobalName uniq mod occ src_loc
322
323         the_app = getFun_wrapper (return_io_wrapper (mkVarApps (Var i) (tvs ++ fe_args)))
324         the_body = mkLams (tvs ++ wrapper_args) the_app
325   
326         (h_stub, c_stub) = fexportEntry (moduleUserString mod)
327                                         ext_name f_helper_glob
328                                         wrapper_arg_tys res_ty cconv isDyn
329      in
330      returnDs (f_helper_glob, (f_helper_glob, the_body), h_stub, c_stub)
331
332   where
333    (tvs,sans_foralls)           = tcSplitForAllTys ty
334    (fe_arg_tys', orig_res_ty)   = tcSplitFunTys sans_foralls
335         -- We must use tcSplits here, because we want to see 
336         -- the (IO t) in the corner of the type!
337
338    fe_arg_tys | isDyn     = tail fe_arg_tys'
339               | otherwise = fe_arg_tys'
340
341    stbl_ptr_ty | isDyn     = head fe_arg_tys'
342                | otherwise = error "stbl_ptr_ty"
343
344    (_, stbl_ptr_ty')            = tcSplitForAllTys stbl_ptr_ty
345    (_, stbl_ptr_to_ty)          = tcSplitAppTy stbl_ptr_ty'
346         -- Again, stable pointers are just newtypes, 
347         -- so we must see them!  Hence tcSplit*
348 \end{code}
349
350 @foreign export dynamic@ lets you dress up Haskell IO actions
351 of some fixed type behind an externally callable interface (i.e.,
352 as a C function pointer). Useful for callbacks and stuff.
353
354 \begin{verbatim}
355 foreign export dynamic f :: (Addr -> Int -> IO Int) -> IO Addr
356
357 -- Haskell-visible constructor, which is generated from the above:
358 -- SUP: No check for NULL from createAdjustor anymore???
359
360 f :: (Addr -> Int -> IO Int) -> IO Addr
361 f cback =
362    bindIO (newStablePtr cback)
363           (\StablePtr sp# -> IO (\s1# ->
364               case _ccall_ createAdjustor cconv sp# ``f_helper'' s1# of
365                  (# s2#, a# #) -> (# s2#, A# a# #)))
366
367 foreign export "f_helper" f_helper :: StablePtr (Addr -> Int -> IO Int) -> Addr -> Int -> IO Int
368 -- `special' foreign export that invokes the closure pointed to by the
369 -- first argument.
370 \end{verbatim}
371
372 \begin{code}
373 dsFExportDynamic :: Module
374                  -> Id
375                  -> CCallConv
376                  -> DsM ([Binding], SDoc, SDoc)
377 dsFExportDynamic mod_name id cconv
378   =  newSysLocalDs ty                                    `thenDs` \ fe_id ->
379      let 
380         -- hack: need to get at the name of the C stub we're about to generate.
381        fe_nm       = _PK_ (moduleUserString mod_name ++ "_" ++ toCName fe_id)
382      in
383      dsFExport mod_name id export_ty fe_nm cconv True   `thenDs` \ (feb, fe, h_code, c_code) ->
384      newSysLocalDs arg_ty                               `thenDs` \ cback ->
385      dsLookupGlobalValue newStablePtrName               `thenDs` \ newStablePtrId ->
386      let
387         mk_stbl_ptr_app    = mkApps (Var newStablePtrId) [ Type arg_ty, Var cback ]
388      in
389      dsLookupGlobalValue bindIOName                     `thenDs` \ bindIOId ->
390      newSysLocalDs (mkTyConApp stablePtrTyCon [arg_ty]) `thenDs` \ stbl_value ->
391      let
392       stbl_app cont ret_ty 
393         = mkApps (Var bindIOId)
394                  [ Type (mkTyConApp stablePtrTyCon [arg_ty])
395                  , Type ret_ty
396                  , mk_stbl_ptr_app
397                  , 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      = [ mkIntLitInt (ccallConvToInt cconv)
408                       , Var stbl_value
409                       , mkLit (MachLabel fe_nm)
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 PlayRisky False io_res_ty        `thenDs` \ ccall_adj ->
416         -- PlayRisky: the adjustor doesn't allocate in the Haskell heap or do a callback
417      let ccall_adj_ty = exprType ccall_adj
418          ccall_io_adj = mkLams [stbl_value]                  $
419                         Note (Coerce io_res_ty ccall_adj_ty)
420                              ccall_adj
421          io_app = mkLams tvs     $
422                   mkLams [cback] $
423                   stbl_app ccall_io_adj res_ty
424          fed = (id `setInlinePragma` NeverActive, io_app)
425                 -- Never inline the f.e.d. function, because the litlit
426                 -- might not be in scope in other modules.
427      in
428      returnDs ([fed, fe], h_code, c_code)
429
430  where
431   ty                    = idType id
432   (tvs,sans_foralls)    = tcSplitForAllTys ty
433   ([arg_ty], io_res_ty) = tcSplitFunTys sans_foralls
434   [res_ty]              = tcTyConAppArgs io_res_ty
435         -- Must use tcSplit* to see the (IO t), which is a newtype
436   export_ty             = mkFunTy (mkTyConApp stablePtrTyCon [arg_ty]) arg_ty
437
438 toCName :: Id -> String
439 toCName i = showSDoc (pprCode CStyle (ppr (idName i)))
440 \end{code}
441
442 %*
443 %
444 \subsection{Generating @foreign export@ stubs}
445 %
446 %*
447
448 For each @foreign export@ function, a C stub function is generated.
449 The C stub constructs the application of the exported Haskell function 
450 using the hugs/ghc rts invocation API.
451
452 \begin{code}
453 fexportEntry :: String
454              -> FAST_STRING
455              -> Id 
456              -> [Type] 
457              -> Type 
458              -> CCallConv 
459              -> Bool
460              -> (SDoc, SDoc)
461 fexportEntry mod_nm c_nm helper args res_ty cc isDyn = (header_bits, c_bits)
462  where
463    -- name of the (Haskell) helper function generated by the desugarer.
464   h_nm      = ppr helper <> text "_closure"
465    -- prototype for the exported function.
466   header_bits = ptext SLIT("extern") <+> fun_proto <> semi
467
468   fun_proto = cResType <+> pprCconv <+> ptext c_nm <>
469               parens (hsep (punctuate comma (zipWith (<+>) cParamTypes proto_args)))
470
471   c_bits =
472     externDecl $$
473     fun_proto  $$
474     vcat 
475      [ lbrace
476      ,   text "SchedulerStatus rc;"
477      ,   declareResult
478           -- create the application + perform it.
479      ,   text "rc=rts_evalIO" <> 
480                   parens (foldl appArg (text "(StgClosure*)&" <> h_nm) (zip args c_args) <> comma <> text "&ret") <> semi
481      ,   text "rts_checkSchedStatus" <> parens (doubleQuotes (ptext c_nm)
482                                                 <> comma <> text "rc") <> semi
483      ,   text "return" <> return_what <> semi
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   res_ty_is_unit = res_ty `eqType` unitTy       -- Look through any newtypes
493
494   cResType | res_ty_is_unit = text "void"
495            | otherwise      = showStgType res_ty
496
497   pprCconv = case cc of
498                 CCallConv   -> empty
499                 StdCallConv -> ppr 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   return_what | res_ty_is_unit = empty
508               | otherwise      = parens (unpackHObj res_ty <> parens (text "ret"))
509
510   c_args = mkCArgNames 0 args
511
512   {-
513    If we're generating an entry point for a 'foreign export ccall dynamic',
514    then we receive the return address of the C function that wants to
515    invoke a Haskell function as any other C function, as second arg.
516    This arg is unused within the body of the generated C stub, but
517    needed by the Adjustor.c code to get the stack cleanup right.
518   -}
519   (proto_args, real_args)
520     = case cc of
521         CCallConv | isDyn -> ( text "a0" : text "a_" : mkCArgNames 1 (tail args)
522                              , head args : addrTy : tail args)
523         other             -> (mkCArgNames 0 args, args)
524
525 mkCArgNames :: Int -> [a] -> [SDoc]
526 mkCArgNames n as = zipWith (\ _ n -> text ('a':show n)) as [n..] 
527
528 mkHObj :: Type -> SDoc
529 mkHObj t = text "rts_mk" <> text (showFFIType t)
530
531 unpackHObj :: Type -> SDoc
532 unpackHObj t = text "rts_get" <> text (showFFIType t)
533
534 showStgType :: Type -> SDoc
535 showStgType t = text "Hs" <> text (showFFIType t)
536
537 showFFIType :: Type -> String
538 showFFIType t = getOccString (getName tc)
539  where
540   tc = case tcSplitTyConApp_maybe (repType t) of
541             Just (tc,_) -> tc
542             Nothing     -> pprPanic "showFFIType" (ppr t)
543 \end{code}