Merge commit '5229c43ccf77bcbffeced01dccb27398d017fa34'
[ghc.git] / compiler / rename / RnSplice.hs
1 {-# LANGUAGE CPP #-}
2 {-# LANGUAGE TypeFamilies #-}
3
4 module RnSplice (
5 rnTopSpliceDecls,
6 rnSpliceType, rnSpliceExpr, rnSplicePat, rnSpliceDecl,
7 rnBracket,
8 checkThLocalName
9 , traceSplice, SpliceInfo(..)
10 ) where
11
12 #include "HsVersions.h"
13
14 import GhcPrelude
15
16 import Name
17 import NameSet
18 import HsSyn
19 import RdrName
20 import TcRnMonad
21
22 import RnEnv
23 import RnUtils ( HsDocContext(..), newLocalBndrRn )
24 import RnUnbound ( isUnboundName )
25 import RnSource ( rnSrcDecls, findSplice )
26 import RnPat ( rnPat )
27 import BasicTypes ( TopLevelFlag, isTopLevel, SourceText(..) )
28 import Outputable
29 import Module
30 import SrcLoc
31 import RnTypes ( rnLHsType )
32
33 import Control.Monad ( unless, when )
34
35 import {-# SOURCE #-} RnExpr ( rnLExpr )
36
37 import TcEnv ( checkWellStaged )
38 import THNames ( liftName )
39
40 import DynFlags
41 import FastString
42 import ErrUtils ( dumpIfSet_dyn_printer )
43 import TcEnv ( tcMetaTy )
44 import Hooks
45 import THNames ( quoteExpName, quotePatName, quoteDecName, quoteTypeName
46 , decsQTyConName, expQTyConName, patQTyConName, typeQTyConName, )
47
48 import {-# SOURCE #-} TcExpr ( tcPolyExpr )
49 import {-# SOURCE #-} TcSplice
50 ( runMetaD
51 , runMetaE
52 , runMetaP
53 , runMetaT
54 , runRemoteModFinalizers
55 , tcTopSpliceExpr
56 )
57
58 import GHCi.RemoteTypes ( ForeignRef )
59 import qualified Language.Haskell.TH as TH (Q)
60
61 import qualified GHC.LanguageExtensions as LangExt
62
63 {-
64 ************************************************************************
65 * *
66 Template Haskell brackets
67 * *
68 ************************************************************************
69 -}
70
71 rnBracket :: HsExpr GhcPs -> HsBracket GhcPs -> RnM (HsExpr GhcRn, FreeVars)
72 rnBracket e br_body
73 = addErrCtxt (quotationCtxtDoc br_body) $
74 do { -- Check that -XTemplateHaskellQuotes is enabled and available
75 thQuotesEnabled <- xoptM LangExt.TemplateHaskellQuotes
76 ; unless thQuotesEnabled $
77 failWith ( vcat
78 [ text "Syntax error on" <+> ppr e
79 , text ("Perhaps you intended to use TemplateHaskell"
80 ++ " or TemplateHaskellQuotes") ] )
81
82 -- Check for nested brackets
83 ; cur_stage <- getStage
84 ; case cur_stage of
85 { Splice Typed -> checkTc (isTypedBracket br_body)
86 illegalUntypedBracket
87 ; Splice Untyped -> checkTc (not (isTypedBracket br_body))
88 illegalTypedBracket
89 ; RunSplice _ ->
90 -- See Note [RunSplice ThLevel] in "TcRnTypes".
91 pprPanic "rnBracket: Renaming bracket when running a splice"
92 (ppr e)
93 ; Comp -> return ()
94 ; Brack {} -> failWithTc illegalBracket
95 }
96
97 -- Brackets are desugared to code that mentions the TH package
98 ; recordThUse
99
100 ; case isTypedBracket br_body of
101 True -> do { traceRn "Renaming typed TH bracket" empty
102 ; (body', fvs_e) <-
103 setStage (Brack cur_stage RnPendingTyped) $
104 rn_bracket cur_stage br_body
105 ; return (HsBracket body', fvs_e) }
106
107 False -> do { traceRn "Renaming untyped TH bracket" empty
108 ; ps_var <- newMutVar []
109 ; (body', fvs_e) <-
110 setStage (Brack cur_stage (RnPendingUntyped ps_var)) $
111 rn_bracket cur_stage br_body
112 ; pendings <- readMutVar ps_var
113 ; return (HsRnBracketOut body' pendings, fvs_e) }
114 }
115
116 rn_bracket :: ThStage -> HsBracket GhcPs -> RnM (HsBracket GhcRn, FreeVars)
117 rn_bracket outer_stage br@(VarBr flg rdr_name)
118 = do { name <- lookupOccRn rdr_name
119 ; this_mod <- getModule
120
121 ; when (flg && nameIsLocalOrFrom this_mod name) $
122 -- Type variables can be quoted in TH. See #5721.
123 do { mb_bind_lvl <- lookupLocalOccThLvl_maybe name
124 ; case mb_bind_lvl of
125 { Nothing -> return () -- Can happen for data constructors,
126 -- but nothing needs to be done for them
127
128 ; Just (top_lvl, bind_lvl) -- See Note [Quoting names]
129 | isTopLevel top_lvl
130 -> when (isExternalName name) (keepAlive name)
131 | otherwise
132 -> do { traceRn "rn_bracket VarBr"
133 (ppr name <+> ppr bind_lvl
134 <+> ppr outer_stage)
135 ; checkTc (thLevel outer_stage + 1 == bind_lvl)
136 (quotedNameStageErr br) }
137 }
138 }
139 ; return (VarBr flg name, unitFV name) }
140
141 rn_bracket _ (ExpBr e) = do { (e', fvs) <- rnLExpr e
142 ; return (ExpBr e', fvs) }
143
144 rn_bracket _ (PatBr p) = rnPat ThPatQuote p $ \ p' -> return (PatBr p', emptyFVs)
145
146 rn_bracket _ (TypBr t) = do { (t', fvs) <- rnLHsType TypBrCtx t
147 ; return (TypBr t', fvs) }
148
149 rn_bracket _ (DecBrL decls)
150 = do { group <- groupDecls decls
151 ; gbl_env <- getGblEnv
152 ; let new_gbl_env = gbl_env { tcg_dus = emptyDUs }
153 -- The emptyDUs is so that we just collect uses for this
154 -- group alone in the call to rnSrcDecls below
155 ; (tcg_env, group') <- setGblEnv new_gbl_env $
156 rnSrcDecls group
157
158 -- Discard the tcg_env; it contains only extra info about fixity
159 ; traceRn "rn_bracket dec" (ppr (tcg_dus tcg_env) $$
160 ppr (duUses (tcg_dus tcg_env)))
161 ; return (DecBrG group', duUses (tcg_dus tcg_env)) }
162 where
163 groupDecls :: [LHsDecl GhcPs] -> RnM (HsGroup GhcPs)
164 groupDecls decls
165 = do { (group, mb_splice) <- findSplice decls
166 ; case mb_splice of
167 { Nothing -> return group
168 ; Just (splice, rest) ->
169 do { group' <- groupDecls rest
170 ; let group'' = appendGroups group group'
171 ; return group'' { hs_splcds = noLoc splice : hs_splcds group' }
172 }
173 }}
174
175 rn_bracket _ (DecBrG _) = panic "rn_bracket: unexpected DecBrG"
176
177 rn_bracket _ (TExpBr e) = do { (e', fvs) <- rnLExpr e
178 ; return (TExpBr e', fvs) }
179
180 quotationCtxtDoc :: HsBracket GhcPs -> SDoc
181 quotationCtxtDoc br_body
182 = hang (text "In the Template Haskell quotation")
183 2 (ppr br_body)
184
185 illegalBracket :: SDoc
186 illegalBracket =
187 text "Template Haskell brackets cannot be nested" <+>
188 text "(without intervening splices)"
189
190 illegalTypedBracket :: SDoc
191 illegalTypedBracket =
192 text "Typed brackets may only appear in typed splices."
193
194 illegalUntypedBracket :: SDoc
195 illegalUntypedBracket =
196 text "Untyped brackets may only appear in untyped splices."
197
198 quotedNameStageErr :: HsBracket GhcPs -> SDoc
199 quotedNameStageErr br
200 = sep [ text "Stage error: the non-top-level quoted name" <+> ppr br
201 , text "must be used at the same stage at which it is bound" ]
202
203
204 {-
205 *********************************************************
206 * *
207 Splices
208 * *
209 *********************************************************
210
211 Note [Free variables of typed splices]
212 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
213 Consider renaming this:
214 f = ...
215 h = ...$(thing "f")...
216
217 where the splice is a *typed* splice. The splice can expand into
218 literally anything, so when we do dependency analysis we must assume
219 that it might mention 'f'. So we simply treat all locally-defined
220 names as mentioned by any splice. This is terribly brutal, but I
221 don't see what else to do. For example, it'll mean that every
222 locally-defined thing will appear to be used, so no unused-binding
223 warnings. But if we miss the dependency, then we might typecheck 'h'
224 before 'f', and that will crash the type checker because 'f' isn't in
225 scope.
226
227 Currently, I'm not treating a splice as also mentioning every import,
228 which is a bit inconsistent -- but there are a lot of them. We might
229 thereby get some bogus unused-import warnings, but we won't crash the
230 type checker. Not very satisfactory really.
231
232 Note [Renamer errors]
233 ~~~~~~~~~~~~~~~~~~~~~
234 It's important to wrap renamer calls in checkNoErrs, because the
235 renamer does not fail for out of scope variables etc. Instead it
236 returns a bogus term/type, so that it can report more than one error.
237 We don't want the type checker to see these bogus unbound variables.
238 -}
239
240 rnSpliceGen :: (HsSplice GhcRn -> RnM (a, FreeVars))
241 -- Outside brackets, run splice
242 -> (HsSplice GhcRn -> (PendingRnSplice, a))
243 -- Inside brackets, make it pending
244 -> HsSplice GhcPs
245 -> RnM (a, FreeVars)
246 rnSpliceGen run_splice pend_splice splice
247 = addErrCtxt (spliceCtxt splice) $ do
248 { stage <- getStage
249 ; case stage of
250 Brack pop_stage RnPendingTyped
251 -> do { checkTc is_typed_splice illegalUntypedSplice
252 ; (splice', fvs) <- setStage pop_stage $
253 rnSplice splice
254 ; let (_pending_splice, result) = pend_splice splice'
255 ; return (result, fvs) }
256
257 Brack pop_stage (RnPendingUntyped ps_var)
258 -> do { checkTc (not is_typed_splice) illegalTypedSplice
259 ; (splice', fvs) <- setStage pop_stage $
260 rnSplice splice
261 ; let (pending_splice, result) = pend_splice splice'
262 ; ps <- readMutVar ps_var
263 ; writeMutVar ps_var (pending_splice : ps)
264 ; return (result, fvs) }
265
266 _ -> do { (splice', fvs1) <- checkNoErrs $
267 setStage (Splice splice_type) $
268 rnSplice splice
269 -- checkNoErrs: don't attempt to run the splice if
270 -- renaming it failed; otherwise we get a cascade of
271 -- errors from e.g. unbound variables
272 ; (result, fvs2) <- run_splice splice'
273 ; return (result, fvs1 `plusFV` fvs2) } }
274 where
275 is_typed_splice = isTypedSplice splice
276 splice_type = if is_typed_splice
277 then Typed
278 else Untyped
279
280 ------------------
281
282 -- | Returns the result of running a splice and the modFinalizers collected
283 -- during the execution.
284 --
285 -- See Note [Delaying modFinalizers in untyped splices].
286 runRnSplice :: UntypedSpliceFlavour
287 -> (LHsExpr GhcTc -> TcRn res)
288 -> (res -> SDoc) -- How to pretty-print res
289 -- Usually just ppr, but not for [Decl]
290 -> HsSplice GhcRn -- Always untyped
291 -> TcRn (res, [ForeignRef (TH.Q ())])
292 runRnSplice flavour run_meta ppr_res splice
293 = do { splice' <- getHooked runRnSpliceHook return >>= ($ splice)
294
295 ; let the_expr = case splice' of
296 HsUntypedSplice _ _ e -> e
297 HsQuasiQuote _ q qs str -> mkQuasiQuoteExpr flavour q qs str
298 HsTypedSplice {} -> pprPanic "runRnSplice" (ppr splice)
299 HsSpliced {} -> pprPanic "runRnSplice" (ppr splice)
300
301 -- Typecheck the expression
302 ; meta_exp_ty <- tcMetaTy meta_ty_name
303 ; zonked_q_expr <- tcTopSpliceExpr Untyped $
304 tcPolyExpr the_expr meta_exp_ty
305
306 -- Run the expression
307 ; mod_finalizers_ref <- newTcRef []
308 ; result <- setStage (RunSplice mod_finalizers_ref) $
309 run_meta zonked_q_expr
310 ; mod_finalizers <- readTcRef mod_finalizers_ref
311 ; traceSplice (SpliceInfo { spliceDescription = what
312 , spliceIsDecl = is_decl
313 , spliceSource = Just the_expr
314 , spliceGenerated = ppr_res result })
315
316 ; return (result, mod_finalizers) }
317
318 where
319 meta_ty_name = case flavour of
320 UntypedExpSplice -> expQTyConName
321 UntypedPatSplice -> patQTyConName
322 UntypedTypeSplice -> typeQTyConName
323 UntypedDeclSplice -> decsQTyConName
324 what = case flavour of
325 UntypedExpSplice -> "expression"
326 UntypedPatSplice -> "pattern"
327 UntypedTypeSplice -> "type"
328 UntypedDeclSplice -> "declarations"
329 is_decl = case flavour of
330 UntypedDeclSplice -> True
331 _ -> False
332
333 ------------------
334 makePending :: UntypedSpliceFlavour
335 -> HsSplice GhcRn
336 -> PendingRnSplice
337 makePending flavour (HsUntypedSplice _ n e)
338 = PendingRnSplice flavour n e
339 makePending flavour (HsQuasiQuote n quoter q_span quote)
340 = PendingRnSplice flavour n (mkQuasiQuoteExpr flavour quoter q_span quote)
341 makePending _ splice@(HsTypedSplice {})
342 = pprPanic "makePending" (ppr splice)
343 makePending _ splice@(HsSpliced {})
344 = pprPanic "makePending" (ppr splice)
345
346 ------------------
347 mkQuasiQuoteExpr :: UntypedSpliceFlavour -> Name -> SrcSpan -> FastString
348 -> LHsExpr GhcRn
349 -- Return the expression (quoter "...quote...")
350 -- which is what we must run in a quasi-quote
351 mkQuasiQuoteExpr flavour quoter q_span quote
352 = L q_span $ HsApp (L q_span $
353 HsApp (L q_span (HsVar (L q_span quote_selector)))
354 quoterExpr)
355 quoteExpr
356 where
357 quoterExpr = L q_span $! HsVar $! (L q_span quoter)
358 quoteExpr = L q_span $! HsLit $! HsString NoSourceText quote
359 quote_selector = case flavour of
360 UntypedExpSplice -> quoteExpName
361 UntypedPatSplice -> quotePatName
362 UntypedTypeSplice -> quoteTypeName
363 UntypedDeclSplice -> quoteDecName
364
365 ---------------------
366 rnSplice :: HsSplice GhcPs -> RnM (HsSplice GhcRn, FreeVars)
367 -- Not exported...used for all
368 rnSplice (HsTypedSplice hasParen splice_name expr)
369 = do { checkTH expr "Template Haskell typed splice"
370 ; loc <- getSrcSpanM
371 ; n' <- newLocalBndrRn (L loc splice_name)
372 ; (expr', fvs) <- rnLExpr expr
373 ; return (HsTypedSplice hasParen n' expr', fvs) }
374
375 rnSplice (HsUntypedSplice hasParen splice_name expr)
376 = do { checkTH expr "Template Haskell untyped splice"
377 ; loc <- getSrcSpanM
378 ; n' <- newLocalBndrRn (L loc splice_name)
379 ; (expr', fvs) <- rnLExpr expr
380 ; return (HsUntypedSplice hasParen n' expr', fvs) }
381
382 rnSplice (HsQuasiQuote splice_name quoter q_loc quote)
383 = do { checkTH quoter "Template Haskell quasi-quote"
384 ; loc <- getSrcSpanM
385 ; splice_name' <- newLocalBndrRn (L loc splice_name)
386
387 -- Rename the quoter; akin to the HsVar case of rnExpr
388 ; quoter' <- lookupOccRn quoter
389 ; this_mod <- getModule
390 ; when (nameIsLocalOrFrom this_mod quoter') $
391 checkThLocalName quoter'
392
393 ; return (HsQuasiQuote splice_name' quoter' q_loc quote, unitFV quoter') }
394
395 rnSplice splice@(HsSpliced {}) = pprPanic "rnSplice" (ppr splice)
396
397 ---------------------
398 rnSpliceExpr :: HsSplice GhcPs -> RnM (HsExpr GhcRn, FreeVars)
399 rnSpliceExpr splice
400 = rnSpliceGen run_expr_splice pend_expr_splice splice
401 where
402 pend_expr_splice :: HsSplice GhcRn -> (PendingRnSplice, HsExpr GhcRn)
403 pend_expr_splice rn_splice
404 = (makePending UntypedExpSplice rn_splice, HsSpliceE rn_splice)
405
406 run_expr_splice :: HsSplice GhcRn -> RnM (HsExpr GhcRn, FreeVars)
407 run_expr_splice rn_splice
408 | isTypedSplice rn_splice -- Run it later, in the type checker
409 = do { -- Ugh! See Note [Splices] above
410 traceRn "rnSpliceExpr: typed expression splice" empty
411 ; lcl_rdr <- getLocalRdrEnv
412 ; gbl_rdr <- getGlobalRdrEnv
413 ; let gbl_names = mkNameSet [gre_name gre | gre <- globalRdrEnvElts gbl_rdr
414 , isLocalGRE gre]
415 lcl_names = mkNameSet (localRdrEnvElts lcl_rdr)
416
417 ; return (HsSpliceE rn_splice, lcl_names `plusFV` gbl_names) }
418
419 | otherwise -- Run it here, see Note [Running splices in the Renamer]
420 = do { traceRn "rnSpliceExpr: untyped expression splice" empty
421 ; (rn_expr, mod_finalizers) <-
422 runRnSplice UntypedExpSplice runMetaE ppr rn_splice
423 ; (lexpr3, fvs) <- checkNoErrs (rnLExpr rn_expr)
424 -- See Note [Delaying modFinalizers in untyped splices].
425 ; return ( HsPar $ HsSpliceE
426 . HsSpliced (ThModFinalizers mod_finalizers)
427 . HsSplicedExpr <$>
428 lexpr3
429 , fvs)
430 }
431
432 {- Note [Running splices in the Renamer]
433 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
434
435 Splices used to be run in the typechecker, which led to (Trac #4364). Since the
436 renamer must decide which expressions depend on which others, and it cannot
437 reliably do this for arbitrary splices, we used to conservatively say that
438 splices depend on all other expressions in scope. Unfortunately, this led to
439 the problem of cyclic type declarations seen in (Trac #4364). Instead, by
440 running splices in the renamer, we side-step the problem of determining
441 dependencies: by the time the dependency analysis happens, any splices have
442 already been run, and expression dependencies can be determined as usual.
443
444 However, see (Trac #9813), for an example where we would like to run splices
445 *after* performing dependency analysis (that is, after renaming). It would be
446 desirable to typecheck "non-splicy" expressions (those expressions that do not
447 contain splices directly or via dependence on an expression that does) before
448 "splicy" expressions, such that types/expressions within the same declaration
449 group would be available to `reify` calls, for example consider the following:
450
451 > module M where
452 > data D = C
453 > f = 1
454 > g = $(mapM reify ['f, 'D, ''C] ...)
455
456 Compilation of this example fails since D/C/f are not in the type environment
457 and thus cannot be reified as they have not been typechecked by the time the
458 splice is renamed and thus run.
459
460 These requirements are at odds: we do not want to run splices in the renamer as
461 we wish to first determine dependencies and typecheck certain expressions,
462 making them available to reify, but cannot accurately determine dependencies
463 without running splices in the renamer!
464
465 Indeed, the conclusion of (Trac #9813) was that it is not worth the complexity
466 to try and
467 a) implement and maintain the code for renaming/typechecking non-splicy
468 expressions before splicy expressions,
469 b) explain to TH users which expressions are/not available to reify at any
470 given point.
471
472 -}
473
474 {- Note [Delaying modFinalizers in untyped splices]
475 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
476
477 When splices run in the renamer, 'reify' does not have access to the local
478 type environment (Trac #11832, [1]).
479
480 For instance, in
481
482 > let x = e in $(reify (mkName "x") >>= runIO . print >> [| return () |])
483
484 'reify' cannot find @x@, because the local type environment is not yet
485 populated. To address this, we allow 'reify' execution to be deferred with
486 'addModFinalizer'.
487
488 > let x = e in $(do addModFinalizer (reify (mkName "x") >>= runIO . print)
489 [| return () |]
490 )
491
492 The finalizer is run with the local type environment when type checking is
493 complete.
494
495 Since the local type environment is not available in the renamer, we annotate
496 the tree at the splice point [2] with @HsSpliceE (HsSpliced finalizers e)@ where
497 @e@ is the result of splicing and @finalizers@ are the finalizers that have been
498 collected during evaluation of the splice [3]. In our example,
499
500 > HsLet
501 > (x = e)
502 > (HsSpliceE $ HsSpliced [reify (mkName "x") >>= runIO . print]
503 > (HsSplicedExpr $ return ())
504 > )
505
506 When the typechecker finds the annotation, it inserts the finalizers in the
507 global environment and exposes the current local environment to them [4, 5, 6].
508
509 > addModFinalizersWithLclEnv [reify (mkName "x") >>= runIO . print]
510
511 References:
512
513 [1] https://ghc.haskell.org/trac/ghc/wiki/TemplateHaskell/Reify
514 [2] 'rnSpliceExpr'
515 [3] 'TcSplice.qAddModFinalizer'
516 [4] 'TcExpr.tcExpr' ('HsSpliceE' ('HsSpliced' ...))
517 [5] 'TcHsType.tc_hs_type' ('HsSpliceTy' ('HsSpliced' ...))
518 [6] 'TcPat.tc_pat' ('SplicePat' ('HsSpliced' ...))
519
520 -}
521
522 ----------------------
523 rnSpliceType :: HsSplice GhcPs -> RnM (HsType GhcRn, FreeVars)
524 rnSpliceType splice
525 = rnSpliceGen run_type_splice pend_type_splice splice
526 where
527 pend_type_splice rn_splice
528 = ( makePending UntypedTypeSplice rn_splice
529 , HsSpliceTy noExt rn_splice)
530
531 run_type_splice rn_splice
532 = do { traceRn "rnSpliceType: untyped type splice" empty
533 ; (hs_ty2, mod_finalizers) <-
534 runRnSplice UntypedTypeSplice runMetaT ppr rn_splice
535 ; (hs_ty3, fvs) <- do { let doc = SpliceTypeCtx hs_ty2
536 ; checkNoErrs $ rnLHsType doc hs_ty2 }
537 -- checkNoErrs: see Note [Renamer errors]
538 -- See Note [Delaying modFinalizers in untyped splices].
539 ; return ( HsParTy noExt $ HsSpliceTy noExt
540 . HsSpliced (ThModFinalizers mod_finalizers)
541 . HsSplicedTy <$>
542 hs_ty3
543 , fvs
544 ) }
545 -- Wrap the result of the splice in parens so that we don't
546 -- lose the outermost location set by runQuasiQuote (#7918)
547
548 {- Note [Partial Type Splices]
549 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
550 Partial Type Signatures are partially supported in TH type splices: only
551 anonymous wild cards are allowed.
552
553 -- ToDo: SLPJ says: I don't understand all this
554
555 Normally, named wild cards are collected before renaming a (partial) type
556 signature. However, TH type splices are run during renaming, i.e. after the
557 initial traversal, leading to out of scope errors for named wild cards. We
558 can't just extend the initial traversal to collect the named wild cards in TH
559 type splices, as we'd need to expand them, which is supposed to happen only
560 once, during renaming.
561
562 Similarly, the extra-constraints wild card is handled right before renaming
563 too, and is therefore also not supported in a TH type splice. Another reason
564 to forbid extra-constraints wild cards in TH type splices is that a single
565 signature can contain many TH type splices, whereas it mustn't contain more
566 than one extra-constraints wild card. Enforcing would this be hard the way
567 things are currently organised.
568
569 Anonymous wild cards pose no problem, because they start out without names and
570 are given names during renaming. These names are collected right after
571 renaming. The names generated for anonymous wild cards in TH type splices will
572 thus be collected as well.
573
574 For more details about renaming wild cards, see RnTypes.rnHsSigWcType
575
576 Note that partial type signatures are fully supported in TH declaration
577 splices, e.g.:
578
579 [d| foo :: _ => _
580 foo x y = x == y |]
581
582 This is because in this case, the partial type signature can be treated as a
583 whole signature, instead of as an arbitrary type.
584
585 -}
586
587
588 ----------------------
589 -- | Rename a splice pattern. See Note [rnSplicePat]
590 rnSplicePat :: HsSplice GhcPs -> RnM ( Either (Pat GhcPs) (Pat GhcRn)
591 , FreeVars)
592 rnSplicePat splice
593 = rnSpliceGen run_pat_splice pend_pat_splice splice
594 where
595 pend_pat_splice rn_splice
596 = (makePending UntypedPatSplice rn_splice
597 , Right (SplicePat noExt rn_splice))
598
599 run_pat_splice rn_splice
600 = do { traceRn "rnSplicePat: untyped pattern splice" empty
601 ; (pat, mod_finalizers) <-
602 runRnSplice UntypedPatSplice runMetaP ppr rn_splice
603 -- See Note [Delaying modFinalizers in untyped splices].
604 ; return ( Left $ ParPat noExt $ (SplicePat noExt)
605 . HsSpliced (ThModFinalizers mod_finalizers)
606 . HsSplicedPat <$>
607 pat
608 , emptyFVs
609 ) }
610 -- Wrap the result of the quasi-quoter in parens so that we don't
611 -- lose the outermost location set by runQuasiQuote (#7918)
612
613 ----------------------
614 rnSpliceDecl :: SpliceDecl GhcPs -> RnM (SpliceDecl GhcRn, FreeVars)
615 rnSpliceDecl (SpliceDecl (L loc splice) flg)
616 = rnSpliceGen run_decl_splice pend_decl_splice splice
617 where
618 pend_decl_splice rn_splice
619 = (makePending UntypedDeclSplice rn_splice, SpliceDecl (L loc rn_splice) flg)
620
621 run_decl_splice rn_splice = pprPanic "rnSpliceDecl" (ppr rn_splice)
622
623 rnTopSpliceDecls :: HsSplice GhcPs -> RnM ([LHsDecl GhcPs], FreeVars)
624 -- Declaration splice at the very top level of the module
625 rnTopSpliceDecls splice
626 = do { (rn_splice, fvs) <- checkNoErrs $
627 setStage (Splice Untyped) $
628 rnSplice splice
629 -- As always, be sure to checkNoErrs above lest we end up with
630 -- holes making it to typechecking, hence #12584.
631 ; traceRn "rnTopSpliceDecls: untyped declaration splice" empty
632 ; (decls, mod_finalizers) <-
633 runRnSplice UntypedDeclSplice runMetaD ppr_decls rn_splice
634 ; add_mod_finalizers_now mod_finalizers
635 ; return (decls,fvs) }
636 where
637 ppr_decls :: [LHsDecl GhcPs] -> SDoc
638 ppr_decls ds = vcat (map ppr ds)
639
640 -- Adds finalizers to the global environment instead of delaying them
641 -- to the type checker.
642 --
643 -- Declaration splices do not have an interesting local environment so
644 -- there is no point in delaying them.
645 --
646 -- See Note [Delaying modFinalizers in untyped splices].
647 add_mod_finalizers_now :: [ForeignRef (TH.Q ())] -> TcRn ()
648 add_mod_finalizers_now [] = return ()
649 add_mod_finalizers_now mod_finalizers = do
650 th_modfinalizers_var <- fmap tcg_th_modfinalizers getGblEnv
651 updTcRef th_modfinalizers_var $ \fins ->
652 runRemoteModFinalizers (ThModFinalizers mod_finalizers) : fins
653
654
655 {-
656 Note [rnSplicePat]
657 ~~~~~~~~~~~~~~~~~~
658 Renaming a pattern splice is a bit tricky, because we need the variables
659 bound in the pattern to be in scope in the RHS of the pattern. This scope
660 management is effectively done by using continuation-passing style in
661 RnPat, through the CpsRn monad. We don't wish to be in that monad here
662 (it would create import cycles and generally conflict with renaming other
663 splices), so we really want to return a (Pat RdrName) -- the result of
664 running the splice -- which can then be further renamed in RnPat, in
665 the CpsRn monad.
666
667 The problem is that if we're renaming a splice within a bracket, we
668 *don't* want to run the splice now. We really do just want to rename
669 it to an HsSplice Name. Of course, then we can't know what variables
670 are bound within the splice. So we accept any unbound variables and
671 rename them again when the bracket is spliced in. If a variable is brought
672 into scope by a pattern splice all is fine. If it is not then an error is
673 reported.
674
675 In any case, when we're done in rnSplicePat, we'll either have a
676 Pat RdrName (the result of running a top-level splice) or a Pat Name
677 (the renamed nested splice). Thus, the awkward return type of
678 rnSplicePat.
679 -}
680
681 spliceCtxt :: HsSplice GhcPs -> SDoc
682 spliceCtxt splice
683 = hang (text "In the" <+> what) 2 (ppr splice)
684 where
685 what = case splice of
686 HsUntypedSplice {} -> text "untyped splice:"
687 HsTypedSplice {} -> text "typed splice:"
688 HsQuasiQuote {} -> text "quasi-quotation:"
689 HsSpliced {} -> text "spliced expression:"
690
691 -- | The splice data to be logged
692 data SpliceInfo
693 = SpliceInfo
694 { spliceDescription :: String
695 , spliceSource :: Maybe (LHsExpr GhcRn) -- Nothing <=> top-level decls
696 -- added by addTopDecls
697 , spliceIsDecl :: Bool -- True <=> put the generate code in a file
698 -- when -dth-dec-file is on
699 , spliceGenerated :: SDoc
700 }
701 -- Note that 'spliceSource' is *renamed* but not *typechecked*
702 -- Reason (a) less typechecking crap
703 -- (b) data constructors after type checking have been
704 -- changed to their *wrappers*, and that makes them
705 -- print always fully qualified
706
707 -- | outputs splice information for 2 flags which have different output formats:
708 -- `-ddump-splices` and `-dth-dec-file`
709 traceSplice :: SpliceInfo -> TcM ()
710 traceSplice (SpliceInfo { spliceDescription = sd, spliceSource = mb_src
711 , spliceGenerated = gen, spliceIsDecl = is_decl })
712 = do { loc <- case mb_src of
713 Nothing -> getSrcSpanM
714 Just (L loc _) -> return loc
715 ; traceOptTcRn Opt_D_dump_splices (spliceDebugDoc loc)
716
717 ; when is_decl $ -- Raw material for -dth-dec-file
718 do { dflags <- getDynFlags
719 ; liftIO $ dumpIfSet_dyn_printer alwaysQualify dflags Opt_D_th_dec_file
720 (spliceCodeDoc loc) } }
721 where
722 -- `-ddump-splices`
723 spliceDebugDoc :: SrcSpan -> SDoc
724 spliceDebugDoc loc
725 = let code = case mb_src of
726 Nothing -> ending
727 Just e -> nest 2 (ppr e) : ending
728 ending = [ text "======>", nest 2 gen ]
729 in hang (ppr loc <> colon <+> text "Splicing" <+> text sd)
730 2 (sep code)
731
732 -- `-dth-dec-file`
733 spliceCodeDoc :: SrcSpan -> SDoc
734 spliceCodeDoc loc
735 = vcat [ text "--" <+> ppr loc <> colon <+> text "Splicing" <+> text sd
736 , gen ]
737
738 illegalTypedSplice :: SDoc
739 illegalTypedSplice = text "Typed splices may not appear in untyped brackets"
740
741 illegalUntypedSplice :: SDoc
742 illegalUntypedSplice = text "Untyped splices may not appear in typed brackets"
743
744 checkThLocalName :: Name -> RnM ()
745 checkThLocalName name
746 | isUnboundName name -- Do not report two errors for
747 = return () -- $(not_in_scope args)
748
749 | otherwise
750 = do { traceRn "checkThLocalName" (ppr name)
751 ; mb_local_use <- getStageAndBindLevel name
752 ; case mb_local_use of {
753 Nothing -> return () ; -- Not a locally-bound thing
754 Just (top_lvl, bind_lvl, use_stage) ->
755 do { let use_lvl = thLevel use_stage
756 ; checkWellStaged (quotes (ppr name)) bind_lvl use_lvl
757 ; traceRn "checkThLocalName" (ppr name <+> ppr bind_lvl
758 <+> ppr use_stage
759 <+> ppr use_lvl)
760 ; checkCrossStageLifting top_lvl bind_lvl use_stage use_lvl name } } }
761
762 --------------------------------------
763 checkCrossStageLifting :: TopLevelFlag -> ThLevel -> ThStage -> ThLevel
764 -> Name -> TcM ()
765 -- We are inside brackets, and (use_lvl > bind_lvl)
766 -- Now we must check whether there's a cross-stage lift to do
767 -- Examples \x -> [| x |]
768 -- [| map |]
769 --
770 -- This code is similar to checkCrossStageLifting in TcExpr, but
771 -- this is only run on *untyped* brackets.
772
773 checkCrossStageLifting top_lvl bind_lvl use_stage use_lvl name
774 | Brack _ (RnPendingUntyped ps_var) <- use_stage -- Only for untyped brackets
775 , use_lvl > bind_lvl -- Cross-stage condition
776 = check_cross_stage_lifting top_lvl name ps_var
777 | otherwise
778 = return ()
779
780 check_cross_stage_lifting :: TopLevelFlag -> Name -> TcRef [PendingRnSplice] -> TcM ()
781 check_cross_stage_lifting top_lvl name ps_var
782 | isTopLevel top_lvl
783 -- Top-level identifiers in this module,
784 -- (which have External Names)
785 -- are just like the imported case:
786 -- no need for the 'lifting' treatment
787 -- E.g. this is fine:
788 -- f x = x
789 -- g y = [| f 3 |]
790 = when (isExternalName name) (keepAlive name)
791 -- See Note [Keeping things alive for Template Haskell]
792
793 | otherwise
794 = -- Nested identifiers, such as 'x' in
795 -- E.g. \x -> [| h x |]
796 -- We must behave as if the reference to x was
797 -- h $(lift x)
798 -- We use 'x' itself as the SplicePointName, used by
799 -- the desugarer to stitch it all back together.
800 -- If 'x' occurs many times we may get many identical
801 -- bindings of the same SplicePointName, but that doesn't
802 -- matter, although it's a mite untidy.
803 do { traceRn "checkCrossStageLifting" (ppr name)
804
805 -- Construct the (lift x) expression
806 ; let lift_expr = nlHsApp (nlHsVar liftName) (nlHsVar name)
807 pend_splice = PendingRnSplice UntypedExpSplice name lift_expr
808
809 -- Update the pending splices
810 ; ps <- readMutVar ps_var
811 ; writeMutVar ps_var (pend_splice : ps) }
812
813 {-
814 Note [Keeping things alive for Template Haskell]
815 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
816 Consider
817 f x = x+1
818 g y = [| f 3 |]
819
820 Here 'f' is referred to from inside the bracket, which turns into data
821 and mentions only f's *name*, not 'f' itself. So we need some other
822 way to keep 'f' alive, lest it get dropped as dead code. That's what
823 keepAlive does. It puts it in the keep-alive set, which subsequently
824 ensures that 'f' stays as a top level binding.
825
826 This must be done by the renamer, not the type checker (as of old),
827 because the type checker doesn't typecheck the body of untyped
828 brackets (Trac #8540).
829
830 A thing can have a bind_lvl of outerLevel, but have an internal name:
831 foo = [d| op = 3
832 bop = op + 1 |]
833 Here the bind_lvl of 'op' is (bogusly) outerLevel, even though it is
834 bound inside a bracket. That is because we don't even even record
835 binding levels for top-level things; the binding levels are in the
836 LocalRdrEnv.
837
838 So the occurrence of 'op' in the rhs of 'bop' looks a bit like a
839 cross-stage thing, but it isn't really. And in fact we never need
840 to do anything here for top-level bound things, so all is fine, if
841 a bit hacky.
842
843 For these chaps (which have Internal Names) we don't want to put
844 them in the keep-alive set.
845
846 Note [Quoting names]
847 ~~~~~~~~~~~~~~~~~~~~
848 A quoted name 'n is a bit like a quoted expression [| n |], except that we
849 have no cross-stage lifting (c.f. TcExpr.thBrackId). So, after incrementing
850 the use-level to account for the brackets, the cases are:
851
852 bind > use Error
853 bind = use+1 OK
854 bind < use
855 Imported things OK
856 Top-level things OK
857 Non-top-level Error
858
859 where 'use' is the binding level of the 'n quote. (So inside the implied
860 bracket the level would be use+1.)
861
862 Examples:
863
864 f 'map -- OK; also for top-level defns of this module
865
866 \x. f 'x -- Not ok (bind = 1, use = 1)
867 -- (whereas \x. f [| x |] might have been ok, by
868 -- cross-stage lifting
869
870 \y. [| \x. $(f 'y) |] -- Not ok (bind =1, use = 1)
871
872 [| \x. $(f 'x) |] -- OK (bind = 2, use = 1)
873 -}