[project @ 2000-11-16 14:43:05 by simonpj]
[ghc-hetmet.git] / ghc / compiler / deSugar / DsForeign.lhs
index d2c20a3..189672a 100644 (file)
@@ -12,42 +12,37 @@ module DsForeign ( dsForeigns ) where
 
 import CoreSyn
 
-import DsCCall         ( dsCCall, mkCCall, boxResult, unboxArg )
+import DsCCall         ( dsCCall, mkCCall, boxResult, unboxArg, resultWrapper )
 import DsMonad
-import DsUtils
 
 import HsSyn           ( ExtName(..), ForeignDecl(..), isDynamicExtName, ForKind(..) )
 import HsDecls         ( extNameStatic )
 import CallConv
 import TcHsSyn         ( TypecheckedForeignDecl )
 import CoreUtils       ( exprType, mkInlineMe )
-import DataCon         ( DataCon, dataConWrapId )
-import Id              ( Id, idType, idName, mkWildId, mkVanillaId, mkSysLocal )
-import MkId            ( mkWorkerId )
+import Id              ( Id, idType, idName, mkVanillaId, mkSysLocal,
+                         setInlinePragma )
+import IdInfo          ( neverInlinePrag )
 import Literal         ( Literal(..) )
 import Module          ( Module, moduleUserString )
 import Name            ( mkGlobalName, nameModule, nameOccName, getOccString, 
                          mkForeignExportOcc, isLocalName,
-                         NamedThing(..), Provenance(..), ExportFlag(..)
+                         NamedThing(..),
                        )
-import Type            ( unUsgTy,
-                         splitTyConApp_maybe, splitFunTys, splitForAllTys,
+import Type            ( repType,
+                         splitTyConApp_maybe, tyConAppTyCon, splitFunTys, splitForAllTys,
                          Type, mkFunTys, mkForAllTys, mkTyConApp,
-                         mkTyVarTy, mkFunTy, splitAppTy, applyTy, funResultTy
+                         mkFunTy, splitAppTy, applyTy, funResultTy
                        )
-import PprType         ( {- instance Outputable Type -} )
-import PrimOp          ( PrimOp(..), CCall(..), CCallTarget(..) )
-import Var             ( TyVar )
-import TysPrim         ( realWorldStatePrimTy, addrPrimTy )
-import TysWiredIn      ( unitTy, addrTy, stablePtrTyCon,
-                         addrDataCon
+import PrimOp          ( CCall(..), CCallTarget(..), dynamicTarget )
+import TysWiredIn      ( unitTy, addrTy, stablePtrTyCon )
+import TysPrim         ( addrPrimTy )
+import PrelNames       ( hasKey, ioTyConKey, deRefStablePtrName, newStablePtrName,
+                         bindIOName, returnIOName
                        )
-import Unique          ( Uniquable(..), hasKey,
-                         ioTyConKey, deRefStablePtrIdKey, returnIOIdKey, 
-                         bindIOIdKey, makeStablePtrIdKey
-               )
-import Maybes          ( maybeToBool )
 import Outputable
+
+import Maybe           ( fromJust )
 \end{code}
 
 Desugaring of @foreign@ declarations is naturally split up into
@@ -64,31 +59,35 @@ is the same as
 so we reuse the desugaring code in @DsCCall@ to deal with these.
 
 \begin{code}
+type Binding = (Id, CoreExpr)  -- No rec/nonrec structure;
+                               -- the occurrence analyser will sort it all out
+
 dsForeigns :: Module
            -> [TypecheckedForeignDecl] 
-          -> DsM ( [CoreBind]        -- desugared foreign imports
-                  , [CoreBind]        -- helper functions for foreign exports
+          -> DsM ( [Id]                -- Foreign-exported binders; 
+                                       -- we have to generate code to register these
+                 , [Binding]
                  , SDoc              -- Header file prototypes for
                                       -- "foreign exported" functions.
                  , SDoc              -- C stubs to use when calling
                                       -- "foreign exported" functions.
                  )
-dsForeigns mod_name fos = foldlDs combine ([],[],empty,empty) fos
+dsForeigns mod_name fos = foldlDs combine ([], [], empty, empty) fos
  where
-  combine (acc_fi, acc_fe, acc_h, acc_c) fo@(ForeignDecl i imp_exp _ ext_nm cconv _) 
+  combine (acc_feb, acc_f, acc_h, acc_c) fo@(ForeignDecl i imp_exp _ ext_nm cconv _) 
     | isForeignImport =   -- foreign import (dynamic)?
         dsFImport i (idType i) uns ext_nm cconv  `thenDs` \ bs -> 
-       returnDs (bs ++ acc_fi, acc_fe, acc_h, acc_c)
+       returnDs (acc_feb, bs ++ acc_f, acc_h, acc_c)
     | isForeignLabel = 
-        dsFLabel i ext_nm `thenDs` \ b -> 
-       returnDs (b:acc_fi, acc_fe, acc_h, acc_c)
+        dsFLabel i (idType i) ext_nm `thenDs` \ b -> 
+       returnDs (acc_feb, b:acc_f, acc_h, acc_c)
     | isDynamicExtName ext_nm =
-        dsFExportDynamic i (idType i) mod_name ext_nm cconv  `thenDs` \ (fi,fe,h,c) -> 
-       returnDs (fi:acc_fi, fe:acc_fe, h $$ acc_h, c $$ acc_c)
+        dsFExportDynamic i (idType i) mod_name ext_nm cconv  `thenDs` \ (feb,bs,h,c) -> 
+       returnDs (feb:acc_feb, bs ++ acc_f, h $$ acc_h, c $$ acc_c)
 
     | otherwise               =  -- foreign export
-        dsFExport i (idType i) mod_name ext_nm cconv False   `thenDs` \ (fe,h,c) ->
-       returnDs (acc_fi, fe:acc_fe, h $$ acc_h, c $$ acc_c)
+        dsFExport i (idType i) mod_name ext_nm cconv False   `thenDs` \ (feb,fe,h,c) ->
+       returnDs (feb:acc_feb, fe:acc_f, h $$ acc_h, c $$ acc_c)
    where
     isForeignImport = 
        case imp_exp of
@@ -129,7 +128,7 @@ dsFImport :: Id
          -> Bool               -- True <=> might cause Haskell GC
          -> ExtName
          -> CallConv
-         -> DsM [CoreBind]
+         -> DsM [Binding]
 dsFImport fn_id ty may_not_gc ext_name cconv 
   = let
        (tvs, fun_ty)        = splitForAllTys ty
@@ -139,14 +138,13 @@ dsFImport fn_id ty may_not_gc ext_name cconv
     mapAndUnzipDs unboxArg (map Var args)      `thenDs` \ (val_args, arg_wrappers) ->
     boxResult io_res_ty                                `thenDs` \ (ccall_result_ty, res_wrapper) ->
 
-    (case ext_name of
-       Dynamic       -> getUniqueDs `thenDs` \ u -> 
-                       returnDs (DynamicTarget u)
-       ExtName fs _  -> returnDs (StaticTarget fs))    `thenDs` \ lbl ->
-
     getUniqueDs                                                `thenDs` \ ccall_uniq ->
     getUniqueDs                                                `thenDs` \ work_uniq ->
     let
+       lbl = case ext_name of
+               Dynamic      -> dynamicTarget
+               ExtName fs _ -> StaticTarget fs
+
        -- Build the worker
        work_arg_ids  = [v | Var v <- val_args]         -- All guaranteed to be vars
        worker_ty     = mkForAllTys tvs (mkFunTys (map idType work_arg_ids) ccall_result_ty)
@@ -160,16 +158,18 @@ dsFImport fn_id ty may_not_gc ext_name cconv
        wrapper_body = foldr ($) (res_wrapper work_app) arg_wrappers
         wrap_rhs     = mkInlineMe (mkLams (tvs ++ args) wrapper_body)
     in
-    returnDs [NonRec fn_id wrap_rhs, NonRec work_id work_rhs]
+    returnDs [(work_id, work_rhs), (fn_id, wrap_rhs)]
 \end{code}
 
 Foreign labels 
 
 \begin{code}
-dsFLabel :: Id -> ExtName -> DsM CoreBind
-dsFLabel nm ext_name = returnDs (NonRec nm fo_rhs)
+dsFLabel :: Id -> Type -> ExtName -> DsM Binding
+dsFLabel nm ty ext_name = 
+   ASSERT(fromJust res_ty == addrPrimTy) -- typechecker ensures this
+   returnDs (nm, fo_rhs (mkLit (MachLabel enm)))
   where
-   fo_rhs = mkConApp addrDataCon [mkLit (MachLitLit enm addrPrimTy)]
+   (res_ty, fo_rhs) = resultWrapper ty
    enm    = extNameStatic ext_name
 \end{code}
 
@@ -192,7 +192,8 @@ dsFExport :: Id
          -> CallConv
          -> Bool               -- True => invoke IO action that's hanging off 
                                -- the first argument's stable pointer
-         -> DsM ( CoreBind
+         -> DsM ( Id           -- The foreign-exported Id
+                , Binding
                 , SDoc
                 , SDoc
                 )
@@ -208,7 +209,7 @@ dsFExport fn_id ty mod_name ext_name cconv isDyn
                 returnDs (\body -> body, orig_res_ty, res_ty)
 
        other ->        -- The function returns t, so wrap the call in returnIO
-                dsLookupGlobalValue returnIOIdKey      `thenDs` \ retIOId ->
+                dsLookupGlobalValue returnIOName       `thenDs` \ retIOId ->
                 returnDs (\body -> mkApps (Var retIOId) [Type orig_res_ty, body],
                           funResultTy (applyTy (idType retIOId) orig_res_ty), 
                                -- We don't have ioTyCon conveniently to hand
@@ -223,8 +224,8 @@ dsFExport fn_id ty mod_name ext_name cconv isDyn
      (if isDyn then 
         newSysLocalDs stbl_ptr_ty                      `thenDs` \ stbl_ptr ->
        newSysLocalDs stbl_ptr_to_ty                    `thenDs` \ stbl_value ->
-       dsLookupGlobalValue deRefStablePtrIdKey         `thenDs` \ deRefStablePtrId ->
-        dsLookupGlobalValue bindIOIdKey                        `thenDs` \ bindIOId ->
+       dsLookupGlobalValue deRefStablePtrName          `thenDs` \ deRefStablePtrId ->
+        dsLookupGlobalValue bindIOName                 `thenDs` \ bindIOId ->
        let
         the_deref_app = mkApps (Var deRefStablePtrId)
                                [ Type stbl_ptr_to_ty, Var stbl_ptr ]
@@ -266,8 +267,7 @@ dsFExport fn_id ty mod_name ext_name cconv isDyn
                         | otherwise        = nameModule name
 
                        occ                 = mkForeignExportOcc (nameOccName name)
-                       prov                = LocalDef src_loc Exported
-                       helper_name         = mkGlobalName uniq mod occ prov
+                       helper_name         = mkGlobalName uniq mod occ src_loc
 
        the_app = getFun_wrapper (return_io_wrapper (mkVarApps (Var i) (tvs ++ fe_args)))
        the_body = mkLams (tvs ++ wrapper_args) the_app
@@ -277,7 +277,7 @@ dsFExport fn_id ty mod_name ext_name cconv isDyn
                                      c_nm f_helper_glob
                                       wrapper_arg_tys res_ty cconv isDyn
      in
-     returnDs (NonRec f_helper_glob the_body, h_stub, c_stub)
+     returnDs (f_helper_glob, (f_helper_glob, the_body), h_stub, c_stub)
 
   where
    (tvs,sans_foralls)                  = splitForAllTys ty
@@ -298,24 +298,17 @@ of some fixed type behind an externally callable interface (i.e.,
 as a C function pointer). Useful for callbacks and stuff.
 
 \begin{verbatim}
-foreign export stdcall f :: (Addr -> Int -> IO Int) -> IO Addr
+foreign export dynamic f :: (Addr -> Int -> IO Int) -> IO Addr
 
--- Haskell-visible constructor, which is generated from the
--- above:
+-- Haskell-visible constructor, which is generated from the above:
+-- SUP: No check for NULL from createAdjustor anymore???
 
 f :: (Addr -> Int -> IO Int) -> IO Addr
-f cback = IO ( \ s1# ->
-  case makeStablePtr# cback s1# of { StateAndStablePtr# s2# sp# ->
-  case _ccall_ "mkAdjustor" sp# ``f_helper'' s2# of
-    StateAndAddr# s3# a# ->
-    case addr2Int# a# of
-      0# -> IOfail s# err
-      _  -> 
-        let
-         a :: Addr
-         a = A# a#
-        in
-         IOok s3# a)
+f cback =
+   bindIO (newStablePtr cback)
+          (\StablePtr sp# -> IO (\s1# ->
+              case _ccall_ createAdjustor cconv sp# ``f_helper'' s1# of
+                 (# s2#, a# #) -> (# s2#, A# a# #)))
 
 foreign export "f_helper" f_helper :: StablePtr (Addr -> Int -> IO Int) -> Addr -> Int -> IO Int
 -- `special' foreign export that invokes the closure pointed to by the
@@ -328,7 +321,7 @@ dsFExportDynamic :: Id
                 -> Module
                 -> ExtName
                 -> CallConv
-                -> DsM (CoreBind, CoreBind, SDoc, SDoc)
+                -> DsM (Id, [Binding], SDoc, SDoc)
 dsFExportDynamic i ty mod_name ext_name cconv =
      newSysLocalDs ty                                   `thenDs` \ fe_id ->
      let 
@@ -337,13 +330,13 @@ dsFExportDynamic i ty mod_name ext_name cconv =
        fe_ext_name = ExtName (_PK_ fe_nm) Nothing
      in
      dsFExport  i export_ty mod_name fe_ext_name cconv True
-     `thenDs` \ (fe@(NonRec fe_helper fe_expr), h_code, c_code) ->
+       `thenDs` \ (feb, fe, h_code, c_code) ->
      newSysLocalDs arg_ty                      `thenDs` \ cback ->
-     dsLookupGlobalValue makeStablePtrIdKey    `thenDs` \ makeStablePtrId ->
+     dsLookupGlobalValue newStablePtrName      `thenDs` \ newStablePtrId ->
      let
-       mk_stbl_ptr_app    = mkApps (Var makeStablePtrId) [ Type arg_ty, Var cback ]
+       mk_stbl_ptr_app    = mkApps (Var newStablePtrId) [ Type arg_ty, Var cback ]
      in
-     dsLookupGlobalValue bindIOIdKey                   `thenDs` \ bindIOId ->
+     dsLookupGlobalValue bindIOName                    `thenDs` \ bindIOId ->
      newSysLocalDs (mkTyConApp stablePtrTyCon [arg_ty]) `thenDs` \ stbl_value ->
      let
       stbl_app cont ret_ty 
@@ -363,23 +356,26 @@ dsFExportDynamic i ty mod_name ext_name cconv =
        -}
       adj_args      = [ mkIntLitInt (callConvToInt cconv)
                      , Var stbl_value
-                     , mkLit (MachLitLit (_PK_ fe_nm) addrPrimTy)
+                     , mkLit (MachLabel (_PK_ fe_nm))
                      ]
         -- name of external entry point providing these services.
        -- (probably in the RTS.) 
       adjustor     = SLIT("createAdjustor")
      in
-     dsCCall adjustor adj_args False False ioAddrTy `thenDs` \ ccall_adj ->
+     dsCCall adjustor adj_args False False io_res_ty `thenDs` \ ccall_adj ->
      let ccall_adj_ty = exprType ccall_adj
          ccall_io_adj = mkLams [stbl_value]                 $
-                       Note (Coerce io_res_ty (unUsgTy ccall_adj_ty))
+                       Note (Coerce io_res_ty ccall_adj_ty)
                             ccall_adj
      in
      let io_app = mkLams tvs    $
                  mkLams [cback] $
-                 stbl_app ccall_io_adj addrTy
+                 stbl_app ccall_io_adj res_ty
+        fed = (i `setInlinePragma` neverInlinePrag, io_app)
+               -- Never inline the f.e.d. function, because the litlit
+               -- might not be in scope in other modules.
      in
-     returnDs (NonRec i io_app, fe, h_code, c_code)
+     returnDs (feb, [fed, fe], h_code, c_code)
 
  where
   (tvs,sans_foralls)              = splitForAllTys ty
@@ -488,12 +484,8 @@ unpackHObj :: Type -> SDoc
 unpackHObj t = text "rts_get" <> text (showFFIType t)
 
 showStgType :: Type -> SDoc
-showStgType t = text "Stg" <> text (showFFIType t)
+showStgType t = text "Hs" <> text (showFFIType t)
 
 showFFIType :: Type -> String
-showFFIType t = getOccString (getName tc)
- where
-  tc = case splitTyConApp_maybe t of
-           Just (tc,_) -> tc
-           Nothing     -> pprPanic "showFFIType" (ppr t)
+showFFIType t = getOccString (getName (tyConAppTyCon t))
 \end{code}