Allow recursive (undecidable) superclasses
[ghc.git] / compiler / main / DynamicLoading.hs
1 {-# LANGUAGE CPP, MagicHash #-}
2
3 -- | Dynamically lookup up values from modules and loading them.
4 module DynamicLoading (
5 #ifdef GHCI
6 -- * Loading plugins
7 loadPlugins,
8 loadFrontendPlugin,
9
10 -- * Force loading information
11 forceLoadModuleInterfaces,
12 forceLoadNameModuleInterface,
13 forceLoadTyCon,
14
15 -- * Finding names
16 lookupRdrNameInModuleForPlugins,
17
18 -- * Loading values
19 getValueSafely,
20 getHValueSafely,
21 lessUnsafeCoerce
22 #endif
23 ) where
24
25 #ifdef GHCI
26 import Linker ( linkModule, getHValue )
27 import SrcLoc ( noSrcSpan )
28 import Finder ( findImportedModule, cannotFindModule )
29 import TcRnMonad ( initTcInteractive, initIfaceTcRn )
30 import LoadIface ( loadPluginInterface )
31 import RdrName ( RdrName, ImportSpec(..), ImpDeclSpec(..)
32 , ImpItemSpec(..), mkGlobalRdrEnv, lookupGRE_RdrName
33 , gre_name, mkRdrQual )
34 import OccName ( OccName, mkVarOcc )
35 import RnNames ( gresFromAvails )
36 import DynFlags
37 import Plugins ( Plugin, FrontendPlugin, CommandLineOption )
38 import PrelNames ( pluginTyConName, frontendPluginTyConName )
39
40 import HscTypes
41 import BasicTypes ( HValue )
42 import Type ( Type, eqType, mkTyConTy, pprTyThingCategory )
43 import TyCon ( TyCon )
44 import Name ( Name, nameModule_maybe )
45 import Id ( idType )
46 import Module ( Module, ModuleName )
47 import Panic
48 import FastString
49 import ErrUtils
50 import Outputable
51 import Exception
52 import Hooks
53
54 import Data.Maybe ( mapMaybe )
55 import GHC.Exts ( unsafeCoerce# )
56
57
58 loadPlugins :: HscEnv -> IO [(ModuleName, Plugin, [CommandLineOption])]
59 loadPlugins hsc_env
60 = do { plugins <- mapM (loadPlugin hsc_env) to_load
61 ; return $ map attachOptions $ to_load `zip` plugins }
62 where
63 dflags = hsc_dflags hsc_env
64 to_load = pluginModNames dflags
65
66 attachOptions (mod_nm, plug) = (mod_nm, plug, options)
67 where
68 options = [ option | (opt_mod_nm, option) <- pluginModNameOpts dflags
69 , opt_mod_nm == mod_nm ]
70
71 loadPlugin :: HscEnv -> ModuleName -> IO Plugin
72 loadPlugin = loadPlugin' (mkVarOcc "plugin") pluginTyConName
73
74 loadFrontendPlugin :: HscEnv -> ModuleName -> IO FrontendPlugin
75 loadFrontendPlugin = loadPlugin' (mkVarOcc "frontendPlugin") frontendPluginTyConName
76
77 loadPlugin' :: OccName -> Name -> HscEnv -> ModuleName -> IO a
78 loadPlugin' occ_name plugin_name hsc_env mod_name
79 = do { let plugin_rdr_name = mkRdrQual mod_name occ_name
80 dflags = hsc_dflags hsc_env
81 ; mb_name <- lookupRdrNameInModuleForPlugins hsc_env mod_name
82 plugin_rdr_name
83 ; case mb_name of {
84 Nothing ->
85 throwGhcExceptionIO (CmdLineError $ showSDoc dflags $ hsep
86 [ ptext (sLit "The module"), ppr mod_name
87 , ptext (sLit "did not export the plugin name")
88 , ppr plugin_rdr_name ]) ;
89 Just name ->
90
91 do { plugin_tycon <- forceLoadTyCon hsc_env plugin_name
92 ; mb_plugin <- getValueSafely hsc_env name (mkTyConTy plugin_tycon)
93 ; case mb_plugin of
94 Nothing ->
95 throwGhcExceptionIO (CmdLineError $ showSDoc dflags $ hsep
96 [ ptext (sLit "The value"), ppr name
97 , ptext (sLit "did not have the type")
98 , ppr pluginTyConName, ptext (sLit "as required")])
99 Just plugin -> return plugin } } }
100
101
102 -- | Force the interfaces for the given modules to be loaded. The 'SDoc' parameter is used
103 -- for debugging (@-ddump-if-trace@) only: it is shown as the reason why the module is being loaded.
104 forceLoadModuleInterfaces :: HscEnv -> SDoc -> [Module] -> IO ()
105 forceLoadModuleInterfaces hsc_env doc modules
106 = (initTcInteractive hsc_env $
107 initIfaceTcRn $
108 mapM_ (loadPluginInterface doc) modules)
109 >> return ()
110
111 -- | Force the interface for the module containing the name to be loaded. The 'SDoc' parameter is used
112 -- for debugging (@-ddump-if-trace@) only: it is shown as the reason why the module is being loaded.
113 forceLoadNameModuleInterface :: HscEnv -> SDoc -> Name -> IO ()
114 forceLoadNameModuleInterface hsc_env reason name = do
115 let name_modules = mapMaybe nameModule_maybe [name]
116 forceLoadModuleInterfaces hsc_env reason name_modules
117
118 -- | Load the 'TyCon' associated with the given name, come hell or high water. Fails if:
119 --
120 -- * The interface could not be loaded
121 -- * The name is not that of a 'TyCon'
122 -- * The name did not exist in the loaded module
123 forceLoadTyCon :: HscEnv -> Name -> IO TyCon
124 forceLoadTyCon hsc_env con_name = do
125 forceLoadNameModuleInterface hsc_env (ptext (sLit "contains a name used in an invocation of loadTyConTy")) con_name
126
127 mb_con_thing <- lookupTypeHscEnv hsc_env con_name
128 case mb_con_thing of
129 Nothing -> throwCmdLineErrorS dflags $ missingTyThingError con_name
130 Just (ATyCon tycon) -> return tycon
131 Just con_thing -> throwCmdLineErrorS dflags $ wrongTyThingError con_name con_thing
132 where dflags = hsc_dflags hsc_env
133
134 -- | Loads the value corresponding to a 'Name' if that value has the given 'Type'. This only provides limited safety
135 -- in that it is up to the user to ensure that that type corresponds to the type you try to use the return value at!
136 --
137 -- If the value found was not of the correct type, returns @Nothing@. Any other condition results in an exception:
138 --
139 -- * If we could not load the names module
140 -- * If the thing being loaded is not a value
141 -- * If the Name does not exist in the module
142 -- * If the link failed
143
144 getValueSafely :: HscEnv -> Name -> Type -> IO (Maybe a)
145 getValueSafely hsc_env val_name expected_type = do
146 mb_hval <- lookupHook getValueSafelyHook getHValueSafely dflags hsc_env val_name expected_type
147 case mb_hval of
148 Nothing -> return Nothing
149 Just hval -> do
150 value <- lessUnsafeCoerce dflags "getValueSafely" hval
151 return (Just value)
152 where
153 dflags = hsc_dflags hsc_env
154
155 getHValueSafely :: HscEnv -> Name -> Type -> IO (Maybe HValue)
156 getHValueSafely hsc_env val_name expected_type = do
157 forceLoadNameModuleInterface hsc_env (ptext (sLit "contains a name used in an invocation of getHValueSafely")) val_name
158 -- Now look up the names for the value and type constructor in the type environment
159 mb_val_thing <- lookupTypeHscEnv hsc_env val_name
160 case mb_val_thing of
161 Nothing -> throwCmdLineErrorS dflags $ missingTyThingError val_name
162 Just (AnId id) -> do
163 -- Check the value type in the interface against the type recovered from the type constructor
164 -- before finally casting the value to the type we assume corresponds to that constructor
165 if expected_type `eqType` idType id
166 then do
167 -- Link in the module that contains the value, if it has such a module
168 case nameModule_maybe val_name of
169 Just mod -> do linkModule hsc_env mod
170 return ()
171 Nothing -> return ()
172 -- Find the value that we just linked in and cast it given that we have proved it's type
173 hval <- getHValue hsc_env val_name
174 return (Just hval)
175 else return Nothing
176 Just val_thing -> throwCmdLineErrorS dflags $ wrongTyThingError val_name val_thing
177 where dflags = hsc_dflags hsc_env
178
179 -- | Coerce a value as usual, but:
180 --
181 -- 1) Evaluate it immediately to get a segfault early if the coercion was wrong
182 --
183 -- 2) Wrap it in some debug messages at verbosity 3 or higher so we can see what happened
184 -- if it /does/ segfault
185 lessUnsafeCoerce :: DynFlags -> String -> a -> IO b
186 lessUnsafeCoerce dflags context what = do
187 debugTraceMsg dflags 3 $ (ptext $ sLit "Coercing a value in") <+> (text context) <> (ptext $ sLit "...")
188 output <- evaluate (unsafeCoerce# what)
189 debugTraceMsg dflags 3 $ ptext $ sLit "Successfully evaluated coercion"
190 return output
191
192
193 -- | Finds the 'Name' corresponding to the given 'RdrName' in the
194 -- context of the 'ModuleName'. Returns @Nothing@ if no such 'Name'
195 -- could be found. Any other condition results in an exception:
196 --
197 -- * If the module could not be found
198 -- * If we could not determine the imports of the module
199 --
200 -- Can only be used for looking up names while loading plugins (and is
201 -- *not* suitable for use within plugins). The interface file is
202 -- loaded very partially: just enough that it can be used, without its
203 -- rules and instances affecting (and being linked from!) the module
204 -- being compiled. This was introduced by 57d6798.
205 --
206 -- See Note [Care with plugin imports] in LoadIface.
207 lookupRdrNameInModuleForPlugins :: HscEnv -> ModuleName -> RdrName -> IO (Maybe Name)
208 lookupRdrNameInModuleForPlugins hsc_env mod_name rdr_name = do
209 -- First find the package the module resides in by searching exposed packages and home modules
210 found_module <- findImportedModule hsc_env mod_name Nothing
211 case found_module of
212 Found _ mod -> do
213 -- Find the exports of the module
214 (_, mb_iface) <- initTcInteractive hsc_env $
215 initIfaceTcRn $
216 loadPluginInterface doc mod
217 case mb_iface of
218 Just iface -> do
219 -- Try and find the required name in the exports
220 let decl_spec = ImpDeclSpec { is_mod = mod_name, is_as = mod_name
221 , is_qual = False, is_dloc = noSrcSpan }
222 imp_spec = ImpSpec decl_spec ImpAll
223 env = mkGlobalRdrEnv (gresFromAvails (Just imp_spec) (mi_exports iface))
224 case lookupGRE_RdrName rdr_name env of
225 [gre] -> return (Just (gre_name gre))
226 [] -> return Nothing
227 _ -> panic "lookupRdrNameInModule"
228
229 Nothing -> throwCmdLineErrorS dflags $ hsep [ptext (sLit "Could not determine the exports of the module"), ppr mod_name]
230 err -> throwCmdLineErrorS dflags $ cannotFindModule dflags mod_name err
231 where
232 dflags = hsc_dflags hsc_env
233 doc = ptext (sLit "contains a name used in an invocation of lookupRdrNameInModule")
234
235 wrongTyThingError :: Name -> TyThing -> SDoc
236 wrongTyThingError name got_thing = hsep [ptext (sLit "The name"), ppr name, ptext (sLit "is not that of a value but rather a"), pprTyThingCategory got_thing]
237
238 missingTyThingError :: Name -> SDoc
239 missingTyThingError name = hsep [ptext (sLit "The name"), ppr name, ptext (sLit "is not in the type environment: are you sure it exists?")]
240
241 throwCmdLineErrorS :: DynFlags -> SDoc -> IO a
242 throwCmdLineErrorS dflags = throwCmdLineError . showSDoc dflags
243
244 throwCmdLineError :: String -> IO a
245 throwCmdLineError = throwGhcExceptionIO . CmdLineError
246 #endif