e9cf0a5e56f06adb43cc0844d39e1172ae59f43a
[ghc.git] / compiler / rename / RnSplice.hs
1 {-# LANGUAGE CPP #-}
2
3 module RnSplice (
4 rnTopSpliceDecls,
5 rnSpliceType, rnSpliceExpr, rnSplicePat, rnSpliceDecl,
6 rnBracket,
7 checkThLocalName
8 ) where
9
10
11 import Name
12 import NameSet
13 import HsSyn
14 import RdrName
15 import TcRnMonad
16 import Kind
17
18 #ifdef GHCI
19 import ErrUtils ( dumpIfSet_dyn_printer )
20 import Control.Monad ( unless, when )
21 import DynFlags
22 import DsMeta ( decsQTyConName, expQTyConName, patQTyConName, typeQTyConName )
23 import LoadIface ( loadInterfaceForName )
24 import Module
25 import RnEnv
26 import RnPat ( rnPat )
27 import RnSource ( rnSrcDecls, findSplice )
28 import RnTypes ( rnLHsType )
29 import SrcLoc
30 import TcEnv ( checkWellStaged, tcMetaTy )
31 import Outputable
32 import BasicTypes ( TopLevelFlag, isTopLevel )
33 import FastString
34 import Hooks
35
36 import {-# SOURCE #-} RnExpr ( rnLExpr )
37 import {-# SOURCE #-} TcExpr ( tcMonoExpr )
38 import {-# SOURCE #-} TcSplice ( runMetaD, runMetaE, runMetaP, runMetaT, tcTopSpliceExpr )
39 #endif
40
41 #ifndef GHCI
42 rnBracket :: HsExpr RdrName -> HsBracket RdrName -> RnM (HsExpr Name, FreeVars)
43 rnBracket e _ = failTH e "Template Haskell bracket"
44
45 rnTopSpliceDecls :: HsSplice RdrName -> RnM ([LHsDecl RdrName], FreeVars)
46 rnTopSpliceDecls e = failTH e "Template Haskell top splice"
47
48 rnSpliceType :: HsSplice RdrName -> PostTc Name Kind
49 -> RnM (HsType Name, FreeVars)
50 rnSpliceType e _ = failTH e "Template Haskell type splice"
51
52 rnSpliceExpr :: Bool -> HsSplice RdrName -> RnM (HsExpr Name, FreeVars)
53 rnSpliceExpr _ e = failTH e "Template Haskell splice"
54
55 rnSplicePat :: HsSplice RdrName -> RnM (Either (Pat RdrName) (Pat Name), FreeVars)
56 rnSplicePat e = failTH e "Template Haskell pattern splice"
57
58 rnSpliceDecl :: SpliceDecl RdrName -> RnM (SpliceDecl Name, FreeVars)
59 rnSpliceDecl e = failTH e "Template Haskell declaration splice"
60 #else
61
62 {-
63 *********************************************************
64 * *
65 Splices
66 * *
67 *********************************************************
68
69 Note [Free variables of typed splices]
70 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
71 Consider renaming this:
72 f = ...
73 h = ...$(thing "f")...
74
75 where the splice is a *typed* splice. The splice can expand into
76 literally anything, so when we do dependency analysis we must assume
77 that it might mention 'f'. So we simply treat all locally-defined
78 names as mentioned by any splice. This is terribly brutal, but I
79 don't see what else to do. For example, it'll mean that every
80 locally-defined thing will appear to be used, so no unused-binding
81 warnings. But if we miss the dependency, then we might typecheck 'h'
82 before 'f', and that will crash the type checker because 'f' isn't in
83 scope.
84
85 Currently, I'm not treating a splice as also mentioning every import,
86 which is a bit inconsistent -- but there are a lot of them. We might
87 thereby get some bogus unused-import warnings, but we won't crash the
88 type checker. Not very satisfactory really.
89
90 Note [Renamer errors]
91 ~~~~~~~~~~~~~~~~~~~~~
92 It's important to wrap renamer calls in checkNoErrs, because the
93 renamer does not fail for out of scope variables etc. Instead it
94 returns a bogus term/type, so that it can report more than one error.
95 We don't want the type checker to see these bogus unbound variables.
96 -}
97
98 rnSpliceGen :: Bool -- Typed splice?
99 -> (HsSplice Name -> RnM (a, FreeVars)) -- Outside brackets, run splice
100 -> (HsSplice Name -> (PendingRnSplice, a)) -- Inside brackets, make it pending
101 -> HsSplice RdrName
102 -> RnM (a, FreeVars)
103 rnSpliceGen is_typed_splice run_splice pend_splice splice@(HsSplice _ expr)
104 = addErrCtxt (spliceCtxt (HsSpliceE is_typed_splice splice)) $
105 setSrcSpan (getLoc expr) $ do
106 { stage <- getStage
107 ; case stage of
108 Brack pop_stage RnPendingTyped
109 -> do { checkTc is_typed_splice illegalUntypedSplice
110 ; (splice', fvs) <- setStage pop_stage $
111 rnSplice splice
112 ; let (_pending_splice, result) = pend_splice splice'
113 ; return (result, fvs) }
114
115 Brack pop_stage (RnPendingUntyped ps_var)
116 -> do { checkTc (not is_typed_splice) illegalTypedSplice
117 ; (splice', fvs) <- setStage pop_stage $
118 rnSplice splice
119 ; let (pending_splice, result) = pend_splice splice'
120 ; ps <- readMutVar ps_var
121 ; writeMutVar ps_var (pending_splice : ps)
122 ; return (result, fvs) }
123
124 _ -> do { (splice', fvs1) <- setStage (Splice is_typed_splice) $
125 rnSplice splice
126
127 ; (result, fvs2) <- run_splice splice'
128 ; return (result, fvs1 `plusFV` fvs2) } }
129
130 ---------------------
131 rnSplice :: HsSplice RdrName -> RnM (HsSplice Name, FreeVars)
132 -- Not exported...used for all
133 rnSplice (HsSplice splice_name expr)
134 = do { checkTH expr "Template Haskell splice"
135 ; loc <- getSrcSpanM
136 ; n' <- newLocalBndrRn (L loc splice_name)
137 ; (expr', fvs) <- rnLExpr expr
138 ; return (HsSplice n' expr', fvs) }
139
140 ---------------------
141 rnSpliceExpr :: Bool -> HsSplice RdrName -> RnM (HsExpr Name, FreeVars)
142 rnSpliceExpr is_typed splice
143 = rnSpliceGen is_typed run_expr_splice pend_expr_splice splice
144 where
145 pend_expr_splice :: HsSplice Name -> (PendingRnSplice, HsExpr Name)
146 pend_expr_splice rn_splice@(HsSplice n e)
147 = (PendingRnExpSplice (PendSplice n e), HsSpliceE is_typed rn_splice)
148
149 run_expr_splice :: HsSplice Name -> RnM (HsExpr Name, FreeVars)
150 run_expr_splice rn_splice@(HsSplice _ expr')
151 | is_typed -- Run it later, in the type checker
152 = do { -- Ugh! See Note [Splices] above
153 lcl_rdr <- getLocalRdrEnv
154 ; gbl_rdr <- getGlobalRdrEnv
155 ; let gbl_names = mkNameSet [gre_name gre | gre <- globalRdrEnvElts gbl_rdr
156 , isLocalGRE gre]
157 lcl_names = mkNameSet (localRdrEnvElts lcl_rdr)
158
159 ; return (HsSpliceE is_typed rn_splice, lcl_names `plusFV` gbl_names) }
160
161 | otherwise -- Run it here
162 = do { expr <- getHooked runRnSpliceHook return >>= ($ expr')
163
164 -- The splice must have type ExpQ
165 ; meta_exp_ty <- tcMetaTy expQTyConName
166
167 -- Typecheck the expression
168 ; zonked_q_expr <- tcTopSpliceExpr False $
169 tcMonoExpr expr meta_exp_ty
170
171 -- Run the expression
172 ; expr2 <- runMetaE zonked_q_expr
173 ; showSplice "expression" expr (ppr expr2)
174
175 ; (lexpr3, fvs) <- checkNoErrs $
176 rnLExpr expr2
177 ; return (unLoc lexpr3, fvs) }
178
179 ----------------------
180 rnSpliceType :: HsSplice RdrName -> PostTc Name Kind
181 -> RnM (HsType Name, FreeVars)
182 rnSpliceType splice k
183 = rnSpliceGen False run_type_splice pend_type_splice splice
184 where
185 pend_type_splice rn_splice@(HsSplice n e)
186 = (PendingRnTypeSplice (PendSplice n e), HsSpliceTy rn_splice k)
187
188 run_type_splice (HsSplice _ expr')
189 = do { expr <- getHooked runRnSpliceHook return >>= ($ expr')
190
191 ; meta_exp_ty <- tcMetaTy typeQTyConName
192
193 -- Typecheck the expression
194 ; zonked_q_expr <- tcTopSpliceExpr False $
195 tcMonoExpr expr meta_exp_ty
196
197 -- Run the expression
198 ; hs_ty2 <- runMetaT zonked_q_expr
199 ; showSplice "type" expr (ppr hs_ty2)
200
201 ; (hs_ty3, fvs) <- do { let doc = SpliceTypeCtx hs_ty2
202 ; checkNoErrs $ rnLHsType doc hs_ty2
203 -- checkNoErrs: see Note [Renamer errors]
204 }
205 ; return (unLoc hs_ty3, fvs) }
206
207 {-
208 Note [rnSplicePat]
209 ~~~~~~~~~~~~~~~~~~
210 Renaming a pattern splice is a bit tricky, because we need the variables
211 bound in the pattern to be in scope in the RHS of the pattern. This scope
212 management is effectively done by using continuation-passing style in
213 RnPat, through the CpsRn monad. We don't wish to be in that monad here
214 (it would create import cycles and generally conflict with renaming other
215 splices), so we really want to return a (Pat RdrName) -- the result of
216 running the splice -- which can then be further renamed in RnPat, in
217 the CpsRn monad.
218
219 The problem is that if we're renaming a splice within a bracket, we
220 *don't* want to run the splice now. We really do just want to rename
221 it to an HsSplice Name. Of course, then we can't know what variables
222 are bound within the splice, so pattern splices within brackets aren't
223 all that useful.
224
225 In any case, when we're done in rnSplicePat, we'll either have a
226 Pat RdrName (the result of running a top-level splice) or a Pat Name
227 (the renamed nested splice). Thus, the awkward return type of
228 rnSplicePat.
229 -}
230
231 -- | Rename a splice pattern. See Note [rnSplicePat]
232 rnSplicePat :: HsSplice RdrName -> RnM ( Either (Pat RdrName) (Pat Name)
233 , FreeVars)
234 rnSplicePat splice
235 = rnSpliceGen False run_pat_splice pend_pat_splice splice
236 where
237 pend_pat_splice rn_splice@(HsSplice n e)
238 = (PendingRnPatSplice (PendSplice n e), Right $ SplicePat rn_splice)
239
240 run_pat_splice (HsSplice _ expr')
241 = do { expr <- getHooked runRnSpliceHook return >>= ($ expr')
242
243 ; meta_exp_ty <- tcMetaTy patQTyConName
244
245 -- Typecheck the expression
246 ; zonked_q_expr <- tcTopSpliceExpr False $
247 tcMonoExpr expr meta_exp_ty
248
249 -- Run the expression
250 ; pat <- runMetaP zonked_q_expr
251 ; showSplice "pattern" expr (ppr pat)
252
253 ; return (Left $ unLoc pat, emptyFVs) }
254
255 ----------------------
256 rnSpliceDecl :: SpliceDecl RdrName -> RnM (SpliceDecl Name, FreeVars)
257 rnSpliceDecl (SpliceDecl (L loc splice) flg)
258 = rnSpliceGen False run_decl_splice pend_decl_splice splice
259 where
260 pend_decl_splice rn_splice@(HsSplice n e)
261 = (PendingRnDeclSplice (PendSplice n e), SpliceDecl(L loc rn_splice) flg)
262
263 run_decl_splice rn_splice = pprPanic "rnSpliceDecl" (ppr rn_splice)
264
265 rnTopSpliceDecls :: HsSplice RdrName -> RnM ([LHsDecl RdrName], FreeVars)
266 -- Declaration splice at the very top level of the module
267 rnTopSpliceDecls (HsSplice _ expr'')
268 = do { (expr, fvs) <- setStage (Splice False) $
269 rnLExpr expr''
270
271 ; expr' <- getHooked runRnSpliceHook return >>= ($ expr)
272
273 ; list_q <- tcMetaTy decsQTyConName -- Q [Dec]
274 ; zonked_q_expr <- tcTopSpliceExpr False (tcMonoExpr expr' list_q)
275
276 -- Run the expression
277 ; decls <- runMetaD zonked_q_expr
278 ; traceSplice $ SpliceInfo True
279 "declarations"
280 (Just (getLoc expr))
281 (Just $ ppr expr')
282 (vcat (map ppr decls))
283
284 ; return (decls,fvs) }
285
286 {-
287 ************************************************************************
288 * *
289 Template Haskell brackets
290 * *
291 ************************************************************************
292 -}
293
294 rnBracket :: HsExpr RdrName -> HsBracket RdrName -> RnM (HsExpr Name, FreeVars)
295 rnBracket e br_body
296 = addErrCtxt (quotationCtxtDoc br_body) $
297 do { -- Check that Template Haskell is enabled and available
298 thEnabled <- xoptM Opt_TemplateHaskell
299 ; unless thEnabled $
300 failWith ( vcat [ ptext (sLit "Syntax error on") <+> ppr e
301 , ptext (sLit "Perhaps you intended to use TemplateHaskell") ] )
302 ; checkTH e "Template Haskell bracket"
303
304 -- Check for nested brackets
305 ; cur_stage <- getStage
306 ; case cur_stage of
307 { Splice True -> checkTc (isTypedBracket br_body) illegalUntypedBracket
308 ; Splice False -> checkTc (not (isTypedBracket br_body)) illegalTypedBracket
309 ; Comp -> return ()
310 ; Brack {} -> failWithTc illegalBracket
311 }
312
313 -- Brackets are desugared to code that mentions the TH package
314 ; recordThUse
315
316 ; case isTypedBracket br_body of
317 True -> do { (body', fvs_e) <- setStage (Brack cur_stage RnPendingTyped) $
318 rn_bracket cur_stage br_body
319 ; return (HsBracket body', fvs_e) }
320
321 False -> do { ps_var <- newMutVar []
322 ; (body', fvs_e) <- setStage (Brack cur_stage (RnPendingUntyped ps_var)) $
323 rn_bracket cur_stage br_body
324 ; pendings <- readMutVar ps_var
325 ; return (HsRnBracketOut body' pendings, fvs_e) }
326 }
327
328 rn_bracket :: ThStage -> HsBracket RdrName -> RnM (HsBracket Name, FreeVars)
329 rn_bracket outer_stage br@(VarBr flg rdr_name)
330 = do { name <- lookupOccRn rdr_name
331 ; this_mod <- getModule
332
333 ; case flg of
334 { -- Type variables can be quoted in TH. See #5721.
335 False -> return ()
336 ; True | nameIsLocalOrFrom this_mod name ->
337 do { mb_bind_lvl <- lookupLocalOccThLvl_maybe name
338 ; case mb_bind_lvl of
339 { Nothing -> return () -- Can happen for data constructors,
340 -- but nothing needs to be done for them
341
342 ; Just (top_lvl, bind_lvl) -- See Note [Quoting names]
343 | isTopLevel top_lvl
344 -> when (isExternalName name) (keepAlive name)
345 | otherwise
346 -> do { traceRn (text "rn_bracket VarBr" <+> ppr name <+> ppr bind_lvl <+> ppr outer_stage)
347 ; checkTc (thLevel outer_stage + 1 == bind_lvl)
348 (quotedNameStageErr br) }
349 }
350 }
351 ; True | otherwise -> -- Imported thing
352 discardResult (loadInterfaceForName msg name)
353 -- Reason for loadInterface: deprecation checking
354 -- assumes that the home interface is loaded, and
355 -- this is the only way that is going to happen
356 }
357 ; return (VarBr flg name, unitFV name) }
358 where
359 msg = ptext (sLit "Need interface for Template Haskell quoted Name")
360
361 rn_bracket _ (ExpBr e) = do { (e', fvs) <- rnLExpr e
362 ; return (ExpBr e', fvs) }
363
364 rn_bracket _ (PatBr p) = rnPat ThPatQuote p $ \ p' -> return (PatBr p', emptyFVs)
365
366 rn_bracket _ (TypBr t) = do { (t', fvs) <- rnLHsType TypBrCtx t
367 ; return (TypBr t', fvs) }
368
369 rn_bracket _ (DecBrL decls)
370 = do { group <- groupDecls decls
371 ; gbl_env <- getGblEnv
372 ; let new_gbl_env = gbl_env { tcg_dus = emptyDUs }
373 -- The emptyDUs is so that we just collect uses for this
374 -- group alone in the call to rnSrcDecls below
375 ; (tcg_env, group') <- setGblEnv new_gbl_env $
376 rnSrcDecls [] group
377 -- The empty list is for extra dependencies coming from .hs-boot files
378 -- See Note [Extra dependencies from .hs-boot files] in RnSource
379
380 -- Discard the tcg_env; it contains only extra info about fixity
381 ; traceRn (text "rn_bracket dec" <+> (ppr (tcg_dus tcg_env) $$
382 ppr (duUses (tcg_dus tcg_env))))
383 ; return (DecBrG group', duUses (tcg_dus tcg_env)) }
384 where
385 groupDecls :: [LHsDecl RdrName] -> RnM (HsGroup RdrName)
386 groupDecls decls
387 = do { (group, mb_splice) <- findSplice decls
388 ; case mb_splice of
389 { Nothing -> return group
390 ; Just (splice, rest) ->
391 do { group' <- groupDecls rest
392 ; let group'' = appendGroups group group'
393 ; return group'' { hs_splcds = noLoc splice : hs_splcds group' }
394 }
395 }}
396
397 rn_bracket _ (DecBrG _) = panic "rn_bracket: unexpected DecBrG"
398
399 rn_bracket _ (TExpBr e) = do { (e', fvs) <- rnLExpr e
400 ; return (TExpBr e', fvs) }
401
402 spliceCtxt :: HsExpr RdrName -> SDoc
403 spliceCtxt expr= hang (ptext (sLit "In the splice:")) 2 (ppr expr)
404
405 showSplice :: String -> LHsExpr Name -> SDoc -> TcM ()
406 -- Note that 'before' is *renamed* but not *typechecked*
407 -- Reason (a) less typechecking crap
408 -- (b) data constructors after type checking have been
409 -- changed to their *wrappers*, and that makes them
410 -- print always fully qualified
411 showSplice what before after =
412 traceSplice $ SpliceInfo False what Nothing (Just $ ppr before) after
413
414 -- | The splice data to be logged
415 --
416 -- duplicates code in TcSplice.hs
417 data SpliceInfo
418 = SpliceInfo
419 { spliceIsDeclaration :: Bool
420 , spliceDescription :: String
421 , spliceLocation :: Maybe SrcSpan
422 , spliceSource :: Maybe SDoc
423 , spliceGenerated :: SDoc
424 }
425
426 -- | outputs splice information for 2 flags which have different output formats:
427 -- `-ddump-splices` and `-dth-dec-file`
428 --
429 -- This duplicates code in TcSplice.hs
430 traceSplice :: SpliceInfo -> TcM ()
431 traceSplice sd = do
432 loc <- case sd of
433 SpliceInfo { spliceLocation = Nothing } -> getSrcSpanM
434 SpliceInfo { spliceLocation = Just loc } -> return loc
435 traceOptTcRn Opt_D_dump_splices (spliceDebugDoc loc sd)
436 when (spliceIsDeclaration sd) $ do
437 dflags <- getDynFlags
438 liftIO $ dumpIfSet_dyn_printer alwaysQualify dflags Opt_D_th_dec_file
439 (spliceCodeDoc loc sd)
440 where
441 -- `-ddump-splices`
442 spliceDebugDoc :: SrcSpan -> SpliceInfo -> SDoc
443 spliceDebugDoc loc sd
444 = let code = case spliceSource sd of
445 Nothing -> ending
446 Just b -> nest 2 b : ending
447 ending = [ text "======>", nest 2 (spliceGenerated sd) ]
448 in (vcat [ ppr loc <> colon
449 <+> text "Splicing" <+> text (spliceDescription sd)
450 , nest 2 (sep code)
451 ])
452
453 -- `-dth-dec-file`
454 spliceCodeDoc :: SrcSpan -> SpliceInfo -> SDoc
455 spliceCodeDoc loc sd
456 = (vcat [ text "--" <+> ppr loc <> colon
457 <+> text "Splicing" <+> text (spliceDescription sd)
458 , sep [spliceGenerated sd]
459 ])
460
461 illegalBracket :: SDoc
462 illegalBracket = ptext (sLit "Template Haskell brackets cannot be nested (without intervening splices)")
463
464 illegalTypedBracket :: SDoc
465 illegalTypedBracket = ptext (sLit "Typed brackets may only appear in typed slices.")
466
467 illegalUntypedBracket :: SDoc
468 illegalUntypedBracket = ptext (sLit "Untyped brackets may only appear in untyped slices.")
469
470 illegalTypedSplice :: SDoc
471 illegalTypedSplice = ptext (sLit "Typed splices may not appear in untyped brackets")
472
473 illegalUntypedSplice :: SDoc
474 illegalUntypedSplice = ptext (sLit "Untyped splices may not appear in typed brackets")
475
476 quotedNameStageErr :: HsBracket RdrName -> SDoc
477 quotedNameStageErr br
478 = sep [ ptext (sLit "Stage error: the non-top-level quoted name") <+> ppr br
479 , ptext (sLit "must be used at the same stage at which is is bound")]
480
481 quotationCtxtDoc :: HsBracket RdrName -> SDoc
482 quotationCtxtDoc br_body
483 = hang (ptext (sLit "In the Template Haskell quotation"))
484 2 (ppr br_body)
485
486 -- spliceResultDoc :: OutputableBndr id => LHsExpr id -> SDoc
487 -- spliceResultDoc expr
488 -- = vcat [ hang (ptext (sLit "In the splice:"))
489 -- 2 (char '$' <> pprParendExpr expr)
490 -- , ptext (sLit "To see what the splice expanded to, use -ddump-splices") ]
491 #endif
492
493 checkThLocalName :: Name -> RnM ()
494 #ifndef GHCI /* GHCI and TH is off */
495 --------------------------------------
496 -- Check for cross-stage lifting
497 checkThLocalName _name
498 = return ()
499
500 #else /* GHCI and TH is on */
501 checkThLocalName name
502 = do { traceRn (text "checkThLocalName" <+> ppr name)
503 ; mb_local_use <- getStageAndBindLevel name
504 ; case mb_local_use of {
505 Nothing -> return () ; -- Not a locally-bound thing
506 Just (top_lvl, bind_lvl, use_stage) ->
507 do { let use_lvl = thLevel use_stage
508 ; checkWellStaged (quotes (ppr name)) bind_lvl use_lvl
509 ; traceRn (text "checkThLocalName" <+> ppr name <+> ppr bind_lvl <+> ppr use_stage <+> ppr use_lvl)
510 ; when (use_lvl > bind_lvl) $
511 checkCrossStageLifting top_lvl name use_stage } } }
512
513 --------------------------------------
514 checkCrossStageLifting :: TopLevelFlag -> Name -> ThStage -> TcM ()
515 -- We are inside brackets, and (use_lvl > bind_lvl)
516 -- Now we must check whether there's a cross-stage lift to do
517 -- Examples \x -> [| x |]
518 -- [| map |]
519
520 checkCrossStageLifting top_lvl name (Brack _ (RnPendingUntyped ps_var))
521 | isTopLevel top_lvl
522 -- Top-level identifiers in this module,
523 -- (which have External Names)
524 -- are just like the imported case:
525 -- no need for the 'lifting' treatment
526 -- E.g. this is fine:
527 -- f x = x
528 -- g y = [| f 3 |]
529 = when (isExternalName name) (keepAlive name)
530 -- See Note [Keeping things alive for Template Haskell]
531
532 | otherwise
533 = -- Nested identifiers, such as 'x' in
534 -- E.g. \x -> [| h x |]
535 -- We must behave as if the reference to x was
536 -- h $(lift x)
537 -- We use 'x' itself as the splice proxy, used by
538 -- the desugarer to stitch it all back together.
539 -- If 'x' occurs many times we may get many identical
540 -- bindings of the same splice proxy, but that doesn't
541 -- matter, although it's a mite untidy.
542 do { traceRn (text "checkCrossStageLifting" <+> ppr name)
543 ; -- Update the pending splices
544 ; ps <- readMutVar ps_var
545 ; writeMutVar ps_var (PendingRnCrossStageSplice name : ps) }
546
547 checkCrossStageLifting _ _ _ = return ()
548 #endif /* GHCI */
549
550 {-
551 Note [Keeping things alive for Template Haskell]
552 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
553 Consider
554 f x = x+1
555 g y = [| f 3 |]
556
557 Here 'f' is referred to from inside the bracket, which turns into data
558 and mentions only f's *name*, not 'f' itself. So we need some other
559 way to keep 'f' alive, lest it get dropped as dead code. That's what
560 keepAlive does. It puts it in the keep-alive set, which subsequently
561 ensures that 'f' stays as a top level binding.
562
563 This must be done by the renamer, not the type checker (as of old),
564 because the type checker doesn't typecheck the body of untyped
565 brackets (Trac #8540).
566
567 A thing can have a bind_lvl of outerLevel, but have an internal name:
568 foo = [d| op = 3
569 bop = op + 1 |]
570 Here the bind_lvl of 'op' is (bogusly) outerLevel, even though it is
571 bound inside a bracket. That is because we don't even even record
572 binding levels for top-level things; the binding levels are in the
573 LocalRdrEnv.
574
575 So the occurrence of 'op' in the rhs of 'bop' looks a bit like a
576 cross-stage thing, but it isn't really. And in fact we never need
577 to do anything here for top-level bound things, so all is fine, if
578 a bit hacky.
579
580 For these chaps (which have Internal Names) we don't want to put
581 them in the keep-alive set.
582
583 Note [Quoting names]
584 ~~~~~~~~~~~~~~~~~~~~
585 A quoted name 'n is a bit like a quoted expression [| n |], except that we
586 have no cross-stage lifting (c.f. TcExpr.thBrackId). So, after incrementing
587 the use-level to account for the brackets, the cases are:
588
589 bind > use Error
590 bind = use+1 OK
591 bind < use
592 Imported things OK
593 Top-level things OK
594 Non-top-level Error
595
596 where 'use' is the binding level of the 'n quote. (So inside the implied
597 bracket the level would be use+1.)
598
599 Examples:
600
601 f 'map -- OK; also for top-level defns of this module
602
603 \x. f 'x -- Not ok (bind = 1, use = 1)
604 -- (whereas \x. f [| x |] might have been ok, by
605 -- cross-stage lifting
606
607 \y. [| \x. $(f 'y) |] -- Not ok (bind =1, use = 1)
608
609 [| \x. $(f 'x) |] -- OK (bind = 2, use = 1)
610 -}