Add Template Haskell support for overloaded labels
[ghc.git] / compiler / hsSyn / HsExpr.hs
1 {-
2 (c) The University of Glasgow 2006
3 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 -}
5
6 {-# LANGUAGE CPP, DeriveDataTypeable, ScopedTypeVariables #-}
7 {-# LANGUAGE StandaloneDeriving #-}
8 {-# LANGUAGE FlexibleContexts #-}
9 {-# LANGUAGE UndecidableInstances #-} -- Note [Pass sensitive types]
10 -- in module PlaceHolder
11 {-# LANGUAGE ConstraintKinds #-}
12 {-# LANGUAGE ExistentialQuantification #-}
13 {-# LANGUAGE DeriveFunctor #-}
14
15 -- | Abstract Haskell syntax for expressions.
16 module HsExpr where
17
18 #include "HsVersions.h"
19
20 -- friends:
21 import HsDecls
22 import HsPat
23 import HsLit
24 import PlaceHolder ( NameOrRdrName )
25 import HsExtension
26 import HsTypes
27 import HsBinds
28
29 -- others:
30 import TcEvidence
31 import CoreSyn
32 import DynFlags ( gopt, GeneralFlag(Opt_PrintExplicitCoercions) )
33 import Name
34 import NameSet
35 import RdrName ( GlobalRdrEnv )
36 import BasicTypes
37 import ConLike
38 import SrcLoc
39 import Util
40 import Outputable
41 import FastString
42 import Type
43
44 -- libraries:
45 import Data.Data hiding (Fixity(..))
46 import qualified Data.Data as Data (Fixity(..))
47 import Data.Maybe (isNothing)
48
49 import GHCi.RemoteTypes ( ForeignRef )
50 import qualified Language.Haskell.TH as TH (Q)
51
52 {-
53 ************************************************************************
54 * *
55 \subsection{Expressions proper}
56 * *
57 ************************************************************************
58 -}
59
60 -- * Expressions proper
61
62 -- | Located Haskell Expression
63 type LHsExpr p = Located (HsExpr p)
64 -- ^ May have 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnComma' when
65 -- in a list
66
67 -- For details on above see note [Api annotations] in ApiAnnotation
68
69 -------------------------
70 -- | Post-Type checking Expression
71 --
72 -- PostTcExpr is an evidence expression attached to the syntax tree by the
73 -- type checker (c.f. postTcType).
74 type PostTcExpr = HsExpr GhcTc
75
76 -- | Post-Type checking Table
77 --
78 -- We use a PostTcTable where there are a bunch of pieces of evidence, more
79 -- than is convenient to keep individually.
80 type PostTcTable = [(Name, PostTcExpr)]
81
82 noPostTcExpr :: PostTcExpr
83 noPostTcExpr = HsLit (HsString noSourceText (fsLit "noPostTcExpr"))
84
85 noPostTcTable :: PostTcTable
86 noPostTcTable = []
87
88 -------------------------
89 -- | Syntax Expression
90 --
91 -- SyntaxExpr is like 'PostTcExpr', but it's filled in a little earlier,
92 -- by the renamer. It's used for rebindable syntax.
93 --
94 -- E.g. @(>>=)@ is filled in before the renamer by the appropriate 'Name' for
95 -- @(>>=)@, and then instantiated by the type checker with its type args
96 -- etc
97 --
98 -- This should desugar to
99 --
100 -- > syn_res_wrap $ syn_expr (syn_arg_wraps[0] arg0)
101 -- > (syn_arg_wraps[1] arg1) ...
102 --
103 -- where the actual arguments come from elsewhere in the AST.
104 -- This could be defined using @PostRn@ and @PostTc@ and such, but it's
105 -- harder to get it all to work out that way. ('noSyntaxExpr' is hard to
106 -- write, for example.)
107 data SyntaxExpr p = SyntaxExpr { syn_expr :: HsExpr p
108 , syn_arg_wraps :: [HsWrapper]
109 , syn_res_wrap :: HsWrapper }
110 deriving instance (DataId p) => Data (SyntaxExpr p)
111
112 -- | This is used for rebindable-syntax pieces that are too polymorphic
113 -- for tcSyntaxOp (trS_fmap and the mzip in ParStmt)
114 noExpr :: SourceTextX p => HsExpr p
115 noExpr = HsLit (HsString (sourceText "noExpr") (fsLit "noExpr"))
116
117 noSyntaxExpr :: SourceTextX p => SyntaxExpr p
118 -- Before renaming, and sometimes after,
119 -- (if the syntax slot makes no sense)
120 noSyntaxExpr = SyntaxExpr { syn_expr = HsLit (HsString noSourceText
121 (fsLit "noSyntaxExpr"))
122 , syn_arg_wraps = []
123 , syn_res_wrap = WpHole }
124
125 -- | Make a 'SyntaxExpr Name' (the "rn" is because this is used in the
126 -- renamer), missing its HsWrappers.
127 mkRnSyntaxExpr :: Name -> SyntaxExpr GhcRn
128 mkRnSyntaxExpr name = SyntaxExpr { syn_expr = HsVar $ noLoc name
129 , syn_arg_wraps = []
130 , syn_res_wrap = WpHole }
131 -- don't care about filling in syn_arg_wraps because we're clearly
132 -- not past the typechecker
133
134 instance (SourceTextX p, OutputableBndrId p) => Outputable (SyntaxExpr p) where
135 ppr (SyntaxExpr { syn_expr = expr
136 , syn_arg_wraps = arg_wraps
137 , syn_res_wrap = res_wrap })
138 = sdocWithDynFlags $ \ dflags ->
139 getPprStyle $ \s ->
140 if debugStyle s || gopt Opt_PrintExplicitCoercions dflags
141 then ppr expr <> braces (pprWithCommas ppr arg_wraps)
142 <> braces (ppr res_wrap)
143 else ppr expr
144
145 -- | Command Syntax Table (for Arrow syntax)
146 type CmdSyntaxTable p = [(Name, HsExpr p)]
147 -- See Note [CmdSyntaxTable]
148
149 {-
150 Note [CmdSyntaxtable]
151 ~~~~~~~~~~~~~~~~~~~~~
152 Used only for arrow-syntax stuff (HsCmdTop), the CmdSyntaxTable keeps
153 track of the methods needed for a Cmd.
154
155 * Before the renamer, this list is an empty list
156
157 * After the renamer, it takes the form @[(std_name, HsVar actual_name)]@
158 For example, for the 'arr' method
159 * normal case: (GHC.Control.Arrow.arr, HsVar GHC.Control.Arrow.arr)
160 * with rebindable syntax: (GHC.Control.Arrow.arr, arr_22)
161 where @arr_22@ is whatever 'arr' is in scope
162
163 * After the type checker, it takes the form [(std_name, <expression>)]
164 where <expression> is the evidence for the method. This evidence is
165 instantiated with the class, but is still polymorphic in everything
166 else. For example, in the case of 'arr', the evidence has type
167 forall b c. (b->c) -> a b c
168 where 'a' is the ambient type of the arrow. This polymorphism is
169 important because the desugarer uses the same evidence at multiple
170 different types.
171
172 This is Less Cool than what we normally do for rebindable syntax, which is to
173 make fully-instantiated piece of evidence at every use site. The Cmd way
174 is Less Cool because
175 * The renamer has to predict which methods are needed.
176 See the tedious RnExpr.methodNamesCmd.
177
178 * The desugarer has to know the polymorphic type of the instantiated
179 method. This is checked by Inst.tcSyntaxName, but is less flexible
180 than the rest of rebindable syntax, where the type is less
181 pre-ordained. (And this flexibility is useful; for example we can
182 typecheck do-notation with (>>=) :: m1 a -> (a -> m2 b) -> m2 b.)
183 -}
184
185 -- | An unbound variable; used for treating out-of-scope variables as
186 -- expression holes
187 data UnboundVar
188 = OutOfScope OccName GlobalRdrEnv -- ^ An (unqualified) out-of-scope
189 -- variable, together with the GlobalRdrEnv
190 -- with respect to which it is unbound
191
192 -- See Note [OutOfScope and GlobalRdrEnv]
193
194 | TrueExprHole OccName -- ^ A "true" expression hole (_ or _x)
195
196 deriving Data
197
198 instance Outputable UnboundVar where
199 ppr = ppr . unboundVarOcc
200
201 unboundVarOcc :: UnboundVar -> OccName
202 unboundVarOcc (OutOfScope occ _) = occ
203 unboundVarOcc (TrueExprHole occ) = occ
204
205 {-
206 Note [OutOfScope and GlobalRdrEnv]
207 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
208 To understand why we bundle a GlobalRdrEnv with an out-of-scope variable,
209 consider the following module:
210
211 module A where
212
213 foo :: ()
214 foo = bar
215
216 bat :: [Double]
217 bat = [1.2, 3.4]
218
219 $(return [])
220
221 bar = ()
222 bad = False
223
224 When A is compiled, the renamer determines that `bar` is not in scope in the
225 declaration of `foo` (since `bar` is declared in the following inter-splice
226 group). Once it has finished typechecking the entire module, the typechecker
227 then generates the associated error message, which specifies both the type of
228 `bar` and a list of possible in-scope alternatives:
229
230 A.hs:6:7: error:
231 • Variable not in scope: bar :: ()
232 • ‘bar’ (line 13) is not in scope before the splice on line 11
233 Perhaps you meant ‘bat’ (line 9)
234
235 When it calls RnEnv.unknownNameSuggestions to identify these alternatives, the
236 typechecker must provide a GlobalRdrEnv. If it provided the current one, which
237 contains top-level declarations for the entire module, the error message would
238 incorrectly suggest the out-of-scope `bar` and `bad` as possible alternatives
239 for `bar` (see Trac #11680). Instead, the typechecker must use the same
240 GlobalRdrEnv the renamer used when it determined that `bar` is out-of-scope.
241
242 To obtain this GlobalRdrEnv, can the typechecker simply use the out-of-scope
243 `bar`'s location to either reconstruct it (from the current GlobalRdrEnv) or to
244 look it up in some global store? Unfortunately, no. The problem is that
245 location information is not always sufficient for this task. This is most
246 apparent when dealing with the TH function addTopDecls, which adds its
247 declarations to the FOLLOWING inter-splice group. Consider these declarations:
248
249 ex9 = cat -- cat is NOT in scope here
250
251 $(do -------------------------------------------------------------
252 ds <- [d| f = cab -- cat and cap are both in scope here
253 cat = ()
254 |]
255 addTopDecls ds
256 [d| g = cab -- only cap is in scope here
257 cap = True
258 |])
259
260 ex10 = cat -- cat is NOT in scope here
261
262 $(return []) -----------------------------------------------------
263
264 ex11 = cat -- cat is in scope
265
266 Here, both occurrences of `cab` are out-of-scope, and so the typechecker needs
267 the GlobalRdrEnvs which were used when they were renamed. These GlobalRdrEnvs
268 are different (`cat` is present only in the GlobalRdrEnv for f's `cab'), but the
269 locations of the two `cab`s are the same (they are both created in the same
270 splice). Thus, we must include some additional information with each `cab` to
271 allow the typechecker to obtain the correct GlobalRdrEnv. Clearly, the simplest
272 information to use is the GlobalRdrEnv itself.
273 -}
274
275 -- | A Haskell expression.
276 data HsExpr p
277 = HsVar (Located (IdP p)) -- ^ Variable
278
279 -- See Note [Located RdrNames]
280
281 | HsUnboundVar UnboundVar -- ^ Unbound variable; also used for "holes"
282 -- (_ or _x).
283 -- Turned from HsVar to HsUnboundVar by the
284 -- renamer, when it finds an out-of-scope
285 -- variable or hole.
286 -- Turned into HsVar by type checker, to support
287 -- deferred type errors.
288
289 | HsConLikeOut ConLike -- ^ After typechecker only; must be different
290 -- HsVar for pretty printing
291
292 | HsRecFld (AmbiguousFieldOcc p) -- ^ Variable pointing to record selector
293 -- Not in use after typechecking
294
295 | HsOverLabel (Maybe (IdP p)) FastString
296 -- ^ Overloaded label (Note [Overloaded labels] in GHC.OverloadedLabels)
297 -- @Just id@ means @RebindableSyntax@ is in use, and gives the id of the
298 -- in-scope 'fromLabel'.
299 -- NB: Not in use after typechecking
300
301 | HsIPVar HsIPName -- ^ Implicit parameter (not in use after typechecking)
302 | HsOverLit (HsOverLit p) -- ^ Overloaded literals
303
304 | HsLit (HsLit p) -- ^ Simple (non-overloaded) literals
305
306 | HsLam (MatchGroup p (LHsExpr p))
307 -- ^ Lambda abstraction. Currently always a single match
308 --
309 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLam',
310 -- 'ApiAnnotation.AnnRarrow',
311
312 -- For details on above see note [Api annotations] in ApiAnnotation
313
314 | HsLamCase (MatchGroup p (LHsExpr p)) -- ^ Lambda-case
315 --
316 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLam',
317 -- 'ApiAnnotation.AnnCase','ApiAnnotation.AnnOpen',
318 -- 'ApiAnnotation.AnnClose'
319
320 -- For details on above see note [Api annotations] in ApiAnnotation
321
322 | HsApp (LHsExpr p) (LHsExpr p) -- ^ Application
323
324 | HsAppType (LHsExpr p) (LHsWcType p) -- ^ Visible type application
325 --
326 -- Explicit type argument; e.g f @Int x y
327 -- NB: Has wildcards, but no implicit quantification
328 --
329 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnAt',
330
331 -- TODO:AZ: Sort out Name
332 | HsAppTypeOut (LHsExpr p) (LHsWcType GhcRn) -- just for pretty-printing
333
334
335 -- | Operator applications:
336 -- NB Bracketed ops such as (+) come out as Vars.
337
338 -- NB We need an expr for the operator in an OpApp/Section since
339 -- the typechecker may need to apply the operator to a few types.
340
341 | OpApp (LHsExpr p) -- left operand
342 (LHsExpr p) -- operator
343 (PostRn p Fixity) -- Renamer adds fixity; bottom until then
344 (LHsExpr p) -- right operand
345
346 -- | Negation operator. Contains the negated expression and the name
347 -- of 'negate'
348 --
349 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnMinus'
350
351 -- For details on above see note [Api annotations] in ApiAnnotation
352 | NegApp (LHsExpr p)
353 (SyntaxExpr p)
354
355 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@,
356 -- 'ApiAnnotation.AnnClose' @')'@
357
358 -- For details on above see note [Api annotations] in ApiAnnotation
359 | HsPar (LHsExpr p) -- ^ Parenthesised expr; see Note [Parens in HsSyn]
360
361 | SectionL (LHsExpr p) -- operand; see Note [Sections in HsSyn]
362 (LHsExpr p) -- operator
363 | SectionR (LHsExpr p) -- operator; see Note [Sections in HsSyn]
364 (LHsExpr p) -- operand
365
366 -- | Used for explicit tuples and sections thereof
367 --
368 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
369 -- 'ApiAnnotation.AnnClose'
370
371 -- For details on above see note [Api annotations] in ApiAnnotation
372 | ExplicitTuple
373 [LHsTupArg p]
374 Boxity
375
376 -- | Used for unboxed sum types
377 --
378 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'(#'@,
379 -- 'ApiAnnotation.AnnVbar', 'ApiAnnotation.AnnClose' @'#)'@,
380 --
381 -- There will be multiple 'ApiAnnotation.AnnVbar', (1 - alternative) before
382 -- the expression, (arity - alternative) after it
383 | ExplicitSum
384 ConTag -- Alternative (one-based)
385 Arity -- Sum arity
386 (LHsExpr p)
387 (PostTc p [Type]) -- the type arguments
388
389 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnCase',
390 -- 'ApiAnnotation.AnnOf','ApiAnnotation.AnnOpen' @'{'@,
391 -- 'ApiAnnotation.AnnClose' @'}'@
392
393 -- For details on above see note [Api annotations] in ApiAnnotation
394 | HsCase (LHsExpr p)
395 (MatchGroup p (LHsExpr p))
396
397 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnIf',
398 -- 'ApiAnnotation.AnnSemi',
399 -- 'ApiAnnotation.AnnThen','ApiAnnotation.AnnSemi',
400 -- 'ApiAnnotation.AnnElse',
401
402 -- For details on above see note [Api annotations] in ApiAnnotation
403 | HsIf (Maybe (SyntaxExpr p)) -- cond function
404 -- Nothing => use the built-in 'if'
405 -- See Note [Rebindable if]
406 (LHsExpr p) -- predicate
407 (LHsExpr p) -- then part
408 (LHsExpr p) -- else part
409
410 -- | Multi-way if
411 --
412 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnIf'
413 -- 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose',
414
415 -- For details on above see note [Api annotations] in ApiAnnotation
416 | HsMultiIf (PostTc p Type) [LGRHS p (LHsExpr p)]
417
418 -- | let(rec)
419 --
420 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLet',
421 -- 'ApiAnnotation.AnnOpen' @'{'@,
422 -- 'ApiAnnotation.AnnClose' @'}'@,'ApiAnnotation.AnnIn'
423
424 -- For details on above see note [Api annotations] in ApiAnnotation
425 | HsLet (LHsLocalBinds p)
426 (LHsExpr p)
427
428 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDo',
429 -- 'ApiAnnotation.AnnOpen', 'ApiAnnotation.AnnSemi',
430 -- 'ApiAnnotation.AnnVbar',
431 -- 'ApiAnnotation.AnnClose'
432
433 -- For details on above see note [Api annotations] in ApiAnnotation
434 | HsDo (HsStmtContext Name) -- The parameterisation is unimportant
435 -- because in this context we never use
436 -- the PatGuard or ParStmt variant
437 (Located [ExprLStmt p]) -- "do":one or more stmts
438 (PostTc p Type) -- Type of the whole expression
439
440 -- | Syntactic list: [a,b,c,...]
441 --
442 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'['@,
443 -- 'ApiAnnotation.AnnClose' @']'@
444
445 -- For details on above see note [Api annotations] in ApiAnnotation
446 | ExplicitList
447 (PostTc p Type) -- Gives type of components of list
448 (Maybe (SyntaxExpr p))
449 -- For OverloadedLists, the fromListN witness
450 [LHsExpr p]
451
452 -- | Syntactic parallel array: [:e1, ..., en:]
453 --
454 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'[:'@,
455 -- 'ApiAnnotation.AnnDotdot','ApiAnnotation.AnnComma',
456 -- 'ApiAnnotation.AnnVbar'
457 -- 'ApiAnnotation.AnnClose' @':]'@
458
459 -- For details on above see note [Api annotations] in ApiAnnotation
460 | ExplicitPArr
461 (PostTc p Type) -- type of elements of the parallel array
462 [LHsExpr p]
463
464 -- | Record construction
465 --
466 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{'@,
467 -- 'ApiAnnotation.AnnDotdot','ApiAnnotation.AnnClose' @'}'@
468
469 -- For details on above see note [Api annotations] in ApiAnnotation
470 | RecordCon
471 { rcon_con_name :: Located (IdP p) -- The constructor name;
472 -- not used after type checking
473 , rcon_con_like :: PostTc p ConLike
474 -- The data constructor or pattern synonym
475 , rcon_con_expr :: PostTcExpr -- Instantiated constructor function
476 , rcon_flds :: HsRecordBinds p } -- The fields
477
478 -- | Record update
479 --
480 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{'@,
481 -- 'ApiAnnotation.AnnDotdot','ApiAnnotation.AnnClose' @'}'@
482
483 -- For details on above see note [Api annotations] in ApiAnnotation
484 | RecordUpd
485 { rupd_expr :: LHsExpr p
486 , rupd_flds :: [LHsRecUpdField p]
487 , rupd_cons :: PostTc p [ConLike]
488 -- Filled in by the type checker to the
489 -- _non-empty_ list of DataCons that have
490 -- all the upd'd fields
491
492 , rupd_in_tys :: PostTc p [Type] -- Argument types of *input* record type
493 , rupd_out_tys :: PostTc p [Type] -- and *output* record type
494 -- The original type can be reconstructed
495 -- with conLikeResTy
496 , rupd_wrap :: PostTc p HsWrapper -- See note [Record Update HsWrapper]
497 }
498 -- For a type family, the arg types are of the *instance* tycon,
499 -- not the family tycon
500
501 -- | Expression with an explicit type signature. @e :: type@
502 --
503 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDcolon'
504
505 -- For details on above see note [Api annotations] in ApiAnnotation
506 | ExprWithTySig
507 (LHsExpr p)
508 (LHsSigWcType p)
509
510 | ExprWithTySigOut -- Post typechecking
511 (LHsExpr p)
512 (LHsSigWcType GhcRn) -- Retain the signature,
513 -- as HsSigType Name, for
514 -- round-tripping purposes
515
516 -- | Arithmetic sequence
517 --
518 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'['@,
519 -- 'ApiAnnotation.AnnComma','ApiAnnotation.AnnDotdot',
520 -- 'ApiAnnotation.AnnClose' @']'@
521
522 -- For details on above see note [Api annotations] in ApiAnnotation
523 | ArithSeq
524 PostTcExpr
525 (Maybe (SyntaxExpr p))
526 -- For OverloadedLists, the fromList witness
527 (ArithSeqInfo p)
528
529 -- | Arithmetic sequence for parallel array
530 --
531 -- > [:e1..e2:] or [:e1, e2..e3:]
532 --
533 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'[:'@,
534 -- 'ApiAnnotation.AnnComma','ApiAnnotation.AnnDotdot',
535 -- 'ApiAnnotation.AnnVbar',
536 -- 'ApiAnnotation.AnnClose' @':]'@
537
538 -- For details on above see note [Api annotations] in ApiAnnotation
539 | PArrSeq
540 PostTcExpr
541 (ArithSeqInfo p)
542
543 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{-\# SCC'@,
544 -- 'ApiAnnotation.AnnVal' or 'ApiAnnotation.AnnValStr',
545 -- 'ApiAnnotation.AnnClose' @'\#-}'@
546
547 -- For details on above see note [Api annotations] in ApiAnnotation
548 | HsSCC SourceText -- Note [Pragma source text] in BasicTypes
549 StringLiteral -- "set cost centre" SCC pragma
550 (LHsExpr p) -- expr whose cost is to be measured
551
552 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{-\# CORE'@,
553 -- 'ApiAnnotation.AnnVal', 'ApiAnnotation.AnnClose' @'\#-}'@
554
555 -- For details on above see note [Api annotations] in ApiAnnotation
556 | HsCoreAnn SourceText -- Note [Pragma source text] in BasicTypes
557 StringLiteral -- hdaume: core annotation
558 (LHsExpr p)
559
560 -----------------------------------------------------------
561 -- MetaHaskell Extensions
562
563 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
564 -- 'ApiAnnotation.AnnOpenE','ApiAnnotation.AnnOpenEQ',
565 -- 'ApiAnnotation.AnnClose','ApiAnnotation.AnnCloseQ'
566
567 -- For details on above see note [Api annotations] in ApiAnnotation
568 | HsBracket (HsBracket p)
569
570 -- See Note [Pending Splices]
571 | HsRnBracketOut
572 (HsBracket GhcRn) -- Output of the renamer is the *original* renamed
573 -- expression, plus
574 [PendingRnSplice] -- _renamed_ splices to be type checked
575
576 | HsTcBracketOut
577 (HsBracket GhcRn) -- Output of the type checker is the *original*
578 -- renamed expression, plus
579 [PendingTcSplice] -- _typechecked_ splices to be
580 -- pasted back in by the desugarer
581
582 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
583 -- 'ApiAnnotation.AnnClose'
584
585 -- For details on above see note [Api annotations] in ApiAnnotation
586 | HsSpliceE (HsSplice p)
587
588 -----------------------------------------------------------
589 -- Arrow notation extension
590
591 -- | @proc@ notation for Arrows
592 --
593 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnProc',
594 -- 'ApiAnnotation.AnnRarrow'
595
596 -- For details on above see note [Api annotations] in ApiAnnotation
597 | HsProc (LPat p) -- arrow abstraction, proc
598 (LHsCmdTop p) -- body of the abstraction
599 -- always has an empty stack
600
601 ---------------------------------------
602 -- static pointers extension
603 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnStatic',
604
605 -- For details on above see note [Api annotations] in ApiAnnotation
606 | HsStatic (PostRn p NameSet) -- Free variables of the body
607 (LHsExpr p) -- Body
608
609 ---------------------------------------
610 -- The following are commands, not expressions proper
611 -- They are only used in the parsing stage and are removed
612 -- immediately in parser.RdrHsSyn.checkCommand
613
614 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.Annlarrowtail',
615 -- 'ApiAnnotation.Annrarrowtail','ApiAnnotation.AnnLarrowtail',
616 -- 'ApiAnnotation.AnnRarrowtail'
617
618 -- For details on above see note [Api annotations] in ApiAnnotation
619 | HsArrApp -- Arrow tail, or arrow application (f -< arg)
620 (LHsExpr p) -- arrow expression, f
621 (LHsExpr p) -- input expression, arg
622 (PostTc p Type) -- type of the arrow expressions f,
623 -- of the form a t t', where arg :: t
624 HsArrAppType -- higher-order (-<<) or first-order (-<)
625 Bool -- True => right-to-left (f -< arg)
626 -- False => left-to-right (arg >- f)
627
628 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpenB' @'(|'@,
629 -- 'ApiAnnotation.AnnCloseB' @'|)'@
630
631 -- For details on above see note [Api annotations] in ApiAnnotation
632 | HsArrForm -- Command formation, (| e cmd1 .. cmdn |)
633 (LHsExpr p) -- the operator
634 -- after type-checking, a type abstraction to be
635 -- applied to the type of the local environment tuple
636 (Maybe Fixity) -- fixity (filled in by the renamer), for forms that
637 -- were converted from OpApp's by the renamer
638 [LHsCmdTop p] -- argument commands
639
640 ---------------------------------------
641 -- Haskell program coverage (Hpc) Support
642
643 | HsTick
644 (Tickish (IdP p))
645 (LHsExpr p) -- sub-expression
646
647 | HsBinTick
648 Int -- module-local tick number for True
649 Int -- module-local tick number for False
650 (LHsExpr p) -- sub-expression
651
652 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
653 -- 'ApiAnnotation.AnnOpen' @'{-\# GENERATED'@,
654 -- 'ApiAnnotation.AnnVal','ApiAnnotation.AnnVal',
655 -- 'ApiAnnotation.AnnColon','ApiAnnotation.AnnVal',
656 -- 'ApiAnnotation.AnnMinus',
657 -- 'ApiAnnotation.AnnVal','ApiAnnotation.AnnColon',
658 -- 'ApiAnnotation.AnnVal',
659 -- 'ApiAnnotation.AnnClose' @'\#-}'@
660
661 -- For details on above see note [Api annotations] in ApiAnnotation
662 | HsTickPragma -- A pragma introduced tick
663 SourceText -- Note [Pragma source text] in BasicTypes
664 (StringLiteral,(Int,Int),(Int,Int))
665 -- external span for this tick
666 ((SourceText,SourceText),(SourceText,SourceText))
667 -- Source text for the four integers used in the span.
668 -- See note [Pragma source text] in BasicTypes
669 (LHsExpr p)
670
671 ---------------------------------------
672 -- These constructors only appear temporarily in the parser.
673 -- The renamer translates them into the Right Thing.
674
675 | EWildPat -- wildcard
676
677 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnAt'
678
679 -- For details on above see note [Api annotations] in ApiAnnotation
680 | EAsPat (Located (IdP p)) -- as pattern
681 (LHsExpr p)
682
683 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnRarrow'
684
685 -- For details on above see note [Api annotations] in ApiAnnotation
686 | EViewPat (LHsExpr p) -- view pattern
687 (LHsExpr p)
688
689 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnTilde'
690
691 -- For details on above see note [Api annotations] in ApiAnnotation
692 | ELazyPat (LHsExpr p) -- ~ pattern
693
694
695 ---------------------------------------
696 -- Finally, HsWrap appears only in typechecker output
697 -- The contained Expr is *NOT* itself an HsWrap.
698 -- See Note [Detecting forced eta expansion] in DsExpr. This invariant
699 -- is maintained by HsUtils.mkHsWrap.
700
701 | HsWrap HsWrapper -- TRANSLATION
702 (HsExpr p)
703
704 deriving instance (DataId p) => Data (HsExpr p)
705
706 -- | Located Haskell Tuple Argument
707 --
708 -- 'HsTupArg' is used for tuple sections
709 -- @(,a,)@ is represented by
710 -- @ExplicitTuple [Missing ty1, Present a, Missing ty3]@
711 -- Which in turn stands for @(\x:ty1 \y:ty2. (x,a,y))@
712 type LHsTupArg id = Located (HsTupArg id)
713 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnComma'
714
715 -- For details on above see note [Api annotations] in ApiAnnotation
716
717 -- | Haskell Tuple Argument
718 data HsTupArg id
719 = Present (LHsExpr id) -- ^ The argument
720 | Missing (PostTc id Type) -- ^ The argument is missing, but this is its type
721 deriving instance (DataId id) => Data (HsTupArg id)
722
723 tupArgPresent :: LHsTupArg id -> Bool
724 tupArgPresent (L _ (Present {})) = True
725 tupArgPresent (L _ (Missing {})) = False
726
727 {-
728 Note [Parens in HsSyn]
729 ~~~~~~~~~~~~~~~~~~~~~~
730 HsPar (and ParPat in patterns, HsParTy in types) is used as follows
731
732 * HsPar is required; the pretty printer does not add parens.
733
734 * HsPars are respected when rearranging operator fixities.
735 So a * (b + c) means what it says (where the parens are an HsPar)
736
737 * For ParPat and HsParTy the pretty printer does add parens but this should be
738 a no-op for ParsedSource, based on the pretty printer round trip feature
739 introduced in
740 https://phabricator.haskell.org/rGHC499e43824bda967546ebf95ee33ec1f84a114a7c
741
742 * ParPat and HsParTy are pretty printed as '( .. )' regardless of whether or
743 not they are strictly necssary. This should be addressed when #13238 is
744 completed, to be treated the same as HsPar.
745
746
747 Note [Sections in HsSyn]
748 ~~~~~~~~~~~~~~~~~~~~~~~~
749 Sections should always appear wrapped in an HsPar, thus
750 HsPar (SectionR ...)
751 The parser parses sections in a wider variety of situations
752 (See Note [Parsing sections]), but the renamer checks for those
753 parens. This invariant makes pretty-printing easier; we don't need
754 a special case for adding the parens round sections.
755
756 Note [Rebindable if]
757 ~~~~~~~~~~~~~~~~~~~~
758 The rebindable syntax for 'if' is a bit special, because when
759 rebindable syntax is *off* we do not want to treat
760 (if c then t else e)
761 as if it was an application (ifThenElse c t e). Why not?
762 Because we allow an 'if' to return *unboxed* results, thus
763 if blah then 3# else 4#
764 whereas that would not be possible using a all to a polymorphic function
765 (because you can't call a polymorphic function at an unboxed type).
766
767 So we use Nothing to mean "use the old built-in typing rule".
768
769 Note [Record Update HsWrapper]
770 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
771 There is a wrapper in RecordUpd which is used for the *required*
772 constraints for pattern synonyms. This wrapper is created in the
773 typechecking and is then directly used in the desugaring without
774 modification.
775
776 For example, if we have the record pattern synonym P,
777 pattern P :: (Show a) => a -> Maybe a
778 pattern P{x} = Just x
779
780 foo = (Just True) { x = False }
781 then `foo` desugars to something like
782 foo = case Just True of
783 P x -> P False
784 hence we need to provide the correct dictionaries to P's matcher on
785 the RHS so that we can build the expression.
786
787 Note [Located RdrNames]
788 ~~~~~~~~~~~~~~~~~~~~~~~
789 A number of syntax elements have seemingly redundant locations attached to them.
790 This is deliberate, to allow transformations making use of the API Annotations
791 to easily correlate a Located Name in the RenamedSource with a Located RdrName
792 in the ParsedSource.
793
794 There are unfortunately enough differences between the ParsedSource and the
795 RenamedSource that the API Annotations cannot be used directly with
796 RenamedSource, so this allows a simple mapping to be used based on the location.
797 -}
798
799 instance (SourceTextX p, OutputableBndrId p) => Outputable (HsExpr p) where
800 ppr expr = pprExpr expr
801
802 -----------------------
803 -- pprExpr, pprLExpr, pprBinds call pprDeeper;
804 -- the underscore versions do not
805 pprLExpr :: (SourceTextX p, OutputableBndrId p) => LHsExpr p -> SDoc
806 pprLExpr (L _ e) = pprExpr e
807
808 pprExpr :: (SourceTextX p, OutputableBndrId p) => HsExpr p -> SDoc
809 pprExpr e | isAtomicHsExpr e || isQuietHsExpr e = ppr_expr e
810 | otherwise = pprDeeper (ppr_expr e)
811
812 isQuietHsExpr :: HsExpr id -> Bool
813 -- Parentheses do display something, but it gives little info and
814 -- if we go deeper when we go inside them then we get ugly things
815 -- like (...)
816 isQuietHsExpr (HsPar _) = True
817 -- applications don't display anything themselves
818 isQuietHsExpr (HsApp _ _) = True
819 isQuietHsExpr (HsAppType _ _) = True
820 isQuietHsExpr (HsAppTypeOut _ _) = True
821 isQuietHsExpr (OpApp _ _ _ _) = True
822 isQuietHsExpr _ = False
823
824 pprBinds :: (SourceTextX idL, SourceTextX idR,
825 OutputableBndrId idL, OutputableBndrId idR)
826 => HsLocalBindsLR idL idR -> SDoc
827 pprBinds b = pprDeeper (ppr b)
828
829 -----------------------
830 ppr_lexpr :: (SourceTextX p, OutputableBndrId p) => LHsExpr p -> SDoc
831 ppr_lexpr e = ppr_expr (unLoc e)
832
833 ppr_expr :: forall p. (SourceTextX p, OutputableBndrId p) => HsExpr p -> SDoc
834 ppr_expr (HsVar (L _ v)) = pprPrefixOcc v
835 ppr_expr (HsUnboundVar uv)= pprPrefixOcc (unboundVarOcc uv)
836 ppr_expr (HsConLikeOut c) = pprPrefixOcc c
837 ppr_expr (HsIPVar v) = ppr v
838 ppr_expr (HsOverLabel _ l)= char '#' <> ppr l
839 ppr_expr (HsLit lit) = ppr lit
840 ppr_expr (HsOverLit lit) = ppr lit
841 ppr_expr (HsPar e) = parens (ppr_lexpr e)
842
843 ppr_expr (HsCoreAnn stc (StringLiteral sta s) e)
844 = vcat [pprWithSourceText stc (text "{-# CORE")
845 <+> pprWithSourceText sta (doubleQuotes $ ftext s) <+> text "#-}"
846 , ppr_lexpr e]
847
848 ppr_expr e@(HsApp {}) = ppr_apps e []
849 ppr_expr e@(HsAppType {}) = ppr_apps e []
850 ppr_expr e@(HsAppTypeOut {}) = ppr_apps e []
851
852 ppr_expr (OpApp e1 op _ e2)
853 | Just pp_op <- should_print_infix (unLoc op)
854 = pp_infixly pp_op
855 | otherwise
856 = pp_prefixly
857
858 where
859 should_print_infix (HsVar (L _ v)) = Just (pprInfixOcc v)
860 should_print_infix (HsConLikeOut c)= Just (pprInfixOcc (conLikeName c))
861 should_print_infix (HsRecFld f) = Just (pprInfixOcc f)
862 should_print_infix (HsUnboundVar h@TrueExprHole{})
863 = Just (pprInfixOcc (unboundVarOcc h))
864 should_print_infix EWildPat = Just (text "`_`")
865 should_print_infix (HsWrap _ e) = should_print_infix e
866 should_print_infix _ = Nothing
867
868 pp_e1 = pprDebugParendExpr e1 -- In debug mode, add parens
869 pp_e2 = pprDebugParendExpr e2 -- to make precedence clear
870
871 pp_prefixly
872 = hang (ppr op) 2 (sep [pp_e1, pp_e2])
873
874 pp_infixly pp_op
875 = hang pp_e1 2 (sep [pp_op, nest 2 pp_e2])
876
877 ppr_expr (NegApp e _) = char '-' <+> pprDebugParendExpr e
878
879 ppr_expr (SectionL expr op)
880 = case unLoc op of
881 HsVar (L _ v) -> pp_infixly v
882 HsConLikeOut c -> pp_infixly (conLikeName c)
883 _ -> pp_prefixly
884 where
885 pp_expr = pprDebugParendExpr expr
886
887 pp_prefixly = hang (hsep [text " \\ x_ ->", ppr op])
888 4 (hsep [pp_expr, text "x_ )"])
889 pp_infixly v = (sep [pp_expr, pprInfixOcc v])
890
891 ppr_expr (SectionR op expr)
892 = case unLoc op of
893 HsVar (L _ v) -> pp_infixly v
894 HsConLikeOut c -> pp_infixly (conLikeName c)
895 _ -> pp_prefixly
896 where
897 pp_expr = pprDebugParendExpr expr
898
899 pp_prefixly = hang (hsep [text "( \\ x_ ->", ppr op, text "x_"])
900 4 (pp_expr <> rparen)
901 pp_infixly v = sep [pprInfixOcc v, pp_expr]
902
903 ppr_expr (ExplicitTuple exprs boxity)
904 = tupleParens (boxityTupleSort boxity) (fcat (ppr_tup_args $ map unLoc exprs))
905 where
906 ppr_tup_args [] = []
907 ppr_tup_args (Present e : es) = (ppr_lexpr e <> punc es) : ppr_tup_args es
908 ppr_tup_args (Missing _ : es) = punc es : ppr_tup_args es
909
910 punc (Present {} : _) = comma <> space
911 punc (Missing {} : _) = comma
912 punc [] = empty
913
914 ppr_expr (ExplicitSum alt arity expr _)
915 = text "(#" <+> ppr_bars (alt - 1) <+> ppr expr <+> ppr_bars (arity - alt) <+> text "#)"
916 where
917 ppr_bars n = hsep (replicate n (char '|'))
918
919 ppr_expr (HsLam matches)
920 = pprMatches matches
921
922 ppr_expr (HsLamCase matches)
923 = sep [ sep [text "\\case"],
924 nest 2 (pprMatches matches) ]
925
926 ppr_expr (HsCase expr matches@(MG { mg_alts = L _ [_] }))
927 = sep [ sep [text "case", nest 4 (ppr expr), ptext (sLit "of {")],
928 nest 2 (pprMatches matches) <+> char '}']
929 ppr_expr (HsCase expr matches)
930 = sep [ sep [text "case", nest 4 (ppr expr), ptext (sLit "of")],
931 nest 2 (pprMatches matches) ]
932
933 ppr_expr (HsIf _ e1 e2 e3)
934 = sep [hsep [text "if", nest 2 (ppr e1), ptext (sLit "then")],
935 nest 4 (ppr e2),
936 text "else",
937 nest 4 (ppr e3)]
938
939 ppr_expr (HsMultiIf _ alts)
940 = hang (text "if") 3 (vcat (map ppr_alt alts))
941 where ppr_alt (L _ (GRHS guards expr)) =
942 hang vbar 2 (ppr_one one_alt)
943 where
944 ppr_one [] = panic "ppr_exp HsMultiIf"
945 ppr_one (h:t) = hang h 2 (sep t)
946 one_alt = [ interpp'SP guards
947 , text "->" <+> pprDeeper (ppr expr) ]
948
949 -- special case: let ... in let ...
950 ppr_expr (HsLet (L _ binds) expr@(L _ (HsLet _ _)))
951 = sep [hang (text "let") 2 (hsep [pprBinds binds, ptext (sLit "in")]),
952 ppr_lexpr expr]
953
954 ppr_expr (HsLet (L _ binds) expr)
955 = sep [hang (text "let") 2 (pprBinds binds),
956 hang (text "in") 2 (ppr expr)]
957
958 ppr_expr (HsDo do_or_list_comp (L _ stmts) _) = pprDo do_or_list_comp stmts
959
960 ppr_expr (ExplicitList _ _ exprs)
961 = brackets (pprDeeperList fsep (punctuate comma (map ppr_lexpr exprs)))
962
963 ppr_expr (ExplicitPArr _ exprs)
964 = paBrackets (pprDeeperList fsep (punctuate comma (map ppr_lexpr exprs)))
965
966 ppr_expr (RecordCon { rcon_con_name = con_id, rcon_flds = rbinds })
967 = hang (ppr con_id) 2 (ppr rbinds)
968
969 ppr_expr (RecordUpd { rupd_expr = L _ aexp, rupd_flds = rbinds })
970 = hang (ppr aexp) 2 (braces (fsep (punctuate comma (map ppr rbinds))))
971
972 ppr_expr (ExprWithTySig expr sig)
973 = hang (nest 2 (ppr_lexpr expr) <+> dcolon)
974 4 (ppr sig)
975 ppr_expr (ExprWithTySigOut expr sig)
976 = hang (nest 2 (ppr_lexpr expr) <+> dcolon)
977 4 (ppr sig)
978
979 ppr_expr (ArithSeq _ _ info) = brackets (ppr info)
980 ppr_expr (PArrSeq _ info) = paBrackets (ppr info)
981
982 ppr_expr EWildPat = char '_'
983 ppr_expr (ELazyPat e) = char '~' <> ppr e
984 ppr_expr (EAsPat v e) = ppr v <> char '@' <> ppr e
985 ppr_expr (EViewPat p e) = ppr p <+> text "->" <+> ppr e
986
987 ppr_expr (HsSCC st (StringLiteral stl lbl) expr)
988 = sep [ pprWithSourceText st (text "{-# SCC")
989 -- no doublequotes if stl empty, for the case where the SCC was written
990 -- without quotes.
991 <+> pprWithSourceText stl (ftext lbl) <+> text "#-}",
992 ppr expr ]
993
994 ppr_expr (HsWrap co_fn e)
995 = pprHsWrapper co_fn (\parens -> if parens then pprExpr e
996 else pprExpr e)
997
998 ppr_expr (HsSpliceE s) = pprSplice s
999 ppr_expr (HsBracket b) = pprHsBracket b
1000 ppr_expr (HsRnBracketOut e []) = ppr e
1001 ppr_expr (HsRnBracketOut e ps) = ppr e $$ text "pending(rn)" <+> ppr ps
1002 ppr_expr (HsTcBracketOut e []) = ppr e
1003 ppr_expr (HsTcBracketOut e ps) = ppr e $$ text "pending(tc)" <+> ppr ps
1004
1005 ppr_expr (HsProc pat (L _ (HsCmdTop cmd _ _ _)))
1006 = hsep [text "proc", ppr pat, ptext (sLit "->"), ppr cmd]
1007
1008 ppr_expr (HsStatic _ e)
1009 = hsep [text "static", ppr e]
1010
1011 ppr_expr (HsTick tickish exp)
1012 = pprTicks (ppr exp) $
1013 ppr tickish <+> ppr_lexpr exp
1014 ppr_expr (HsBinTick tickIdTrue tickIdFalse exp)
1015 = pprTicks (ppr exp) $
1016 hcat [text "bintick<",
1017 ppr tickIdTrue,
1018 text ",",
1019 ppr tickIdFalse,
1020 text ">(",
1021 ppr exp, text ")"]
1022 ppr_expr (HsTickPragma _ externalSrcLoc _ exp)
1023 = pprTicks (ppr exp) $
1024 hcat [text "tickpragma<",
1025 pprExternalSrcLoc externalSrcLoc,
1026 text ">(",
1027 ppr exp,
1028 text ")"]
1029
1030 ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp True)
1031 = hsep [ppr_lexpr arrow, larrowt, ppr_lexpr arg]
1032 ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp False)
1033 = hsep [ppr_lexpr arg, arrowt, ppr_lexpr arrow]
1034 ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp True)
1035 = hsep [ppr_lexpr arrow, larrowtt, ppr_lexpr arg]
1036 ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp False)
1037 = hsep [ppr_lexpr arg, arrowtt, ppr_lexpr arrow]
1038
1039 ppr_expr (HsArrForm (L _ (HsVar (L _ v))) (Just _) [arg1, arg2])
1040 = sep [pprCmdArg (unLoc arg1), hsep [pprInfixOcc v, pprCmdArg (unLoc arg2)]]
1041 ppr_expr (HsArrForm (L _ (HsConLikeOut c)) (Just _) [arg1, arg2])
1042 = sep [pprCmdArg (unLoc arg1), hsep [pprInfixOcc (conLikeName c), pprCmdArg (unLoc arg2)]]
1043 ppr_expr (HsArrForm op _ args)
1044 = hang (text "(|" <+> ppr_lexpr op)
1045 4 (sep (map (pprCmdArg.unLoc) args) <+> text "|)")
1046 ppr_expr (HsRecFld f) = ppr f
1047
1048 -- We must tiresomely make the "id" parameter to the LHsWcType existential
1049 -- because it's different in the HsAppType case and the HsAppTypeOut case
1050 -- | Located Haskell Wildcard Type Expression
1051 data LHsWcTypeX = forall p. (SourceTextX p, OutputableBndrId p)
1052 => LHsWcTypeX (LHsWcType p)
1053
1054 ppr_apps :: (SourceTextX p, OutputableBndrId p) => HsExpr p
1055 -> [Either (LHsExpr p) LHsWcTypeX]
1056 -> SDoc
1057 ppr_apps (HsApp (L _ fun) arg) args
1058 = ppr_apps fun (Left arg : args)
1059 ppr_apps (HsAppType (L _ fun) arg) args
1060 = ppr_apps fun (Right (LHsWcTypeX arg) : args)
1061 ppr_apps (HsAppTypeOut (L _ fun) arg) args
1062 = ppr_apps fun (Right (LHsWcTypeX arg) : args)
1063 ppr_apps fun args = hang (ppr_expr fun) 2 (sep (map pp args))
1064 where
1065 pp (Left arg) = ppr arg
1066 pp (Right (LHsWcTypeX (HsWC { hswc_body = L _ arg })))
1067 = char '@' <> pprHsType arg
1068
1069 pprExternalSrcLoc :: (StringLiteral,(Int,Int),(Int,Int)) -> SDoc
1070 pprExternalSrcLoc (StringLiteral _ src,(n1,n2),(n3,n4))
1071 = ppr (src,(n1,n2),(n3,n4))
1072
1073 {-
1074 HsSyn records exactly where the user put parens, with HsPar.
1075 So generally speaking we print without adding any parens.
1076 However, some code is internally generated, and in some places
1077 parens are absolutely required; so for these places we use
1078 pprParendLExpr (but don't print double parens of course).
1079
1080 For operator applications we don't add parens, because the operator
1081 fixities should do the job, except in debug mode (-dppr-debug) so we
1082 can see the structure of the parse tree.
1083 -}
1084
1085 pprDebugParendExpr :: (SourceTextX p, OutputableBndrId p) => LHsExpr p -> SDoc
1086 pprDebugParendExpr expr
1087 = getPprStyle (\sty ->
1088 if debugStyle sty then pprParendLExpr expr
1089 else pprLExpr expr)
1090
1091 pprParendLExpr :: (SourceTextX p, OutputableBndrId p) => LHsExpr p -> SDoc
1092 pprParendLExpr (L _ e) = pprParendExpr e
1093
1094 pprParendExpr :: (SourceTextX p, OutputableBndrId p) => HsExpr p -> SDoc
1095 pprParendExpr expr
1096 | hsExprNeedsParens expr = parens (pprExpr expr)
1097 | otherwise = pprExpr expr
1098 -- Using pprLExpr makes sure that we go 'deeper'
1099 -- I think that is usually (always?) right
1100
1101 hsExprNeedsParens :: HsExpr id -> Bool
1102 -- True of expressions for which '(e)' and 'e'
1103 -- mean the same thing
1104 hsExprNeedsParens (ArithSeq {}) = False
1105 hsExprNeedsParens (PArrSeq {}) = False
1106 hsExprNeedsParens (HsLit {}) = False
1107 hsExprNeedsParens (HsOverLit {}) = False
1108 hsExprNeedsParens (HsVar {}) = False
1109 hsExprNeedsParens (HsUnboundVar {}) = False
1110 hsExprNeedsParens (HsConLikeOut {}) = False
1111 hsExprNeedsParens (HsIPVar {}) = False
1112 hsExprNeedsParens (HsOverLabel {}) = False
1113 hsExprNeedsParens (ExplicitTuple {}) = False
1114 hsExprNeedsParens (ExplicitList {}) = False
1115 hsExprNeedsParens (ExplicitPArr {}) = False
1116 hsExprNeedsParens (HsPar {}) = False
1117 hsExprNeedsParens (HsBracket {}) = False
1118 hsExprNeedsParens (HsRnBracketOut {}) = False
1119 hsExprNeedsParens (HsTcBracketOut {}) = False
1120 hsExprNeedsParens (HsDo sc _ _)
1121 | isListCompExpr sc = False
1122 hsExprNeedsParens (HsRecFld{}) = False
1123 hsExprNeedsParens (RecordCon{}) = False
1124 hsExprNeedsParens (HsSpliceE{}) = False
1125 hsExprNeedsParens (RecordUpd{}) = False
1126 hsExprNeedsParens (HsWrap _ e) = hsExprNeedsParens e
1127 hsExprNeedsParens _ = True
1128
1129
1130 isAtomicHsExpr :: HsExpr id -> Bool
1131 -- True of a single token
1132 isAtomicHsExpr (HsVar {}) = True
1133 isAtomicHsExpr (HsConLikeOut {}) = True
1134 isAtomicHsExpr (HsLit {}) = True
1135 isAtomicHsExpr (HsOverLit {}) = True
1136 isAtomicHsExpr (HsIPVar {}) = True
1137 isAtomicHsExpr (HsOverLabel {}) = True
1138 isAtomicHsExpr (HsUnboundVar {}) = True
1139 isAtomicHsExpr (HsWrap _ e) = isAtomicHsExpr e
1140 isAtomicHsExpr (HsPar e) = isAtomicHsExpr (unLoc e)
1141 isAtomicHsExpr (HsRecFld{}) = True
1142 isAtomicHsExpr _ = False
1143
1144 {-
1145 ************************************************************************
1146 * *
1147 \subsection{Commands (in arrow abstractions)}
1148 * *
1149 ************************************************************************
1150
1151 We re-use HsExpr to represent these.
1152 -}
1153
1154 -- | Located Haskell Command (for arrow syntax)
1155 type LHsCmd id = Located (HsCmd id)
1156
1157 -- | Haskell Command (e.g. a "statement" in an Arrow proc block)
1158 data HsCmd id
1159 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.Annlarrowtail',
1160 -- 'ApiAnnotation.Annrarrowtail','ApiAnnotation.AnnLarrowtail',
1161 -- 'ApiAnnotation.AnnRarrowtail'
1162
1163 -- For details on above see note [Api annotations] in ApiAnnotation
1164 = HsCmdArrApp -- Arrow tail, or arrow application (f -< arg)
1165 (LHsExpr id) -- arrow expression, f
1166 (LHsExpr id) -- input expression, arg
1167 (PostTc id Type) -- type of the arrow expressions f,
1168 -- of the form a t t', where arg :: t
1169 HsArrAppType -- higher-order (-<<) or first-order (-<)
1170 Bool -- True => right-to-left (f -< arg)
1171 -- False => left-to-right (arg >- f)
1172
1173 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpenB' @'(|'@,
1174 -- 'ApiAnnotation.AnnCloseB' @'|)'@
1175
1176 -- For details on above see note [Api annotations] in ApiAnnotation
1177 | HsCmdArrForm -- Command formation, (| e cmd1 .. cmdn |)
1178 (LHsExpr id) -- The operator.
1179 -- After type-checking, a type abstraction to be
1180 -- applied to the type of the local environment tuple
1181 LexicalFixity -- Whether the operator appeared prefix or infix when
1182 -- parsed.
1183 (Maybe Fixity) -- fixity (filled in by the renamer), for forms that
1184 -- were converted from OpApp's by the renamer
1185 [LHsCmdTop id] -- argument commands
1186
1187 | HsCmdApp (LHsCmd id)
1188 (LHsExpr id)
1189
1190 | HsCmdLam (MatchGroup id (LHsCmd id)) -- kappa
1191 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLam',
1192 -- 'ApiAnnotation.AnnRarrow',
1193
1194 -- For details on above see note [Api annotations] in ApiAnnotation
1195
1196 | HsCmdPar (LHsCmd id) -- parenthesised command
1197 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@,
1198 -- 'ApiAnnotation.AnnClose' @')'@
1199
1200 -- For details on above see note [Api annotations] in ApiAnnotation
1201
1202 | HsCmdCase (LHsExpr id)
1203 (MatchGroup id (LHsCmd id)) -- bodies are HsCmd's
1204 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnCase',
1205 -- 'ApiAnnotation.AnnOf','ApiAnnotation.AnnOpen' @'{'@,
1206 -- 'ApiAnnotation.AnnClose' @'}'@
1207
1208 -- For details on above see note [Api annotations] in ApiAnnotation
1209
1210 | HsCmdIf (Maybe (SyntaxExpr id)) -- cond function
1211 (LHsExpr id) -- predicate
1212 (LHsCmd id) -- then part
1213 (LHsCmd id) -- else part
1214 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnIf',
1215 -- 'ApiAnnotation.AnnSemi',
1216 -- 'ApiAnnotation.AnnThen','ApiAnnotation.AnnSemi',
1217 -- 'ApiAnnotation.AnnElse',
1218
1219 -- For details on above see note [Api annotations] in ApiAnnotation
1220
1221 | HsCmdLet (LHsLocalBinds id) -- let(rec)
1222 (LHsCmd id)
1223 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLet',
1224 -- 'ApiAnnotation.AnnOpen' @'{'@,
1225 -- 'ApiAnnotation.AnnClose' @'}'@,'ApiAnnotation.AnnIn'
1226
1227 -- For details on above see note [Api annotations] in ApiAnnotation
1228
1229 | HsCmdDo (Located [CmdLStmt id])
1230 (PostTc id Type) -- Type of the whole expression
1231 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDo',
1232 -- 'ApiAnnotation.AnnOpen', 'ApiAnnotation.AnnSemi',
1233 -- 'ApiAnnotation.AnnVbar',
1234 -- 'ApiAnnotation.AnnClose'
1235
1236 -- For details on above see note [Api annotations] in ApiAnnotation
1237
1238 | HsCmdWrap HsWrapper
1239 (HsCmd id) -- If cmd :: arg1 --> res
1240 -- wrap :: arg1 "->" arg2
1241 -- Then (HsCmdWrap wrap cmd) :: arg2 --> res
1242 deriving instance (DataId id) => Data (HsCmd id)
1243
1244 -- | Haskell Array Application Type
1245 data HsArrAppType = HsHigherOrderApp | HsFirstOrderApp
1246 deriving Data
1247
1248
1249 {- | Top-level command, introducing a new arrow.
1250 This may occur inside a proc (where the stack is empty) or as an
1251 argument of a command-forming operator.
1252 -}
1253
1254 -- | Located Haskell Top-level Command
1255 type LHsCmdTop p = Located (HsCmdTop p)
1256
1257 -- | Haskell Top-level Command
1258 data HsCmdTop p
1259 = HsCmdTop (LHsCmd p)
1260 (PostTc p Type) -- Nested tuple of inputs on the command's stack
1261 (PostTc p Type) -- return type of the command
1262 (CmdSyntaxTable p) -- See Note [CmdSyntaxTable]
1263 deriving instance (DataId p) => Data (HsCmdTop p)
1264
1265 instance (SourceTextX p, OutputableBndrId p) => Outputable (HsCmd p) where
1266 ppr cmd = pprCmd cmd
1267
1268 -----------------------
1269 -- pprCmd and pprLCmd call pprDeeper;
1270 -- the underscore versions do not
1271 pprLCmd :: (SourceTextX p, OutputableBndrId p) => LHsCmd p -> SDoc
1272 pprLCmd (L _ c) = pprCmd c
1273
1274 pprCmd :: (SourceTextX p, OutputableBndrId p) => HsCmd p -> SDoc
1275 pprCmd c | isQuietHsCmd c = ppr_cmd c
1276 | otherwise = pprDeeper (ppr_cmd c)
1277
1278 isQuietHsCmd :: HsCmd id -> Bool
1279 -- Parentheses do display something, but it gives little info and
1280 -- if we go deeper when we go inside them then we get ugly things
1281 -- like (...)
1282 isQuietHsCmd (HsCmdPar _) = True
1283 -- applications don't display anything themselves
1284 isQuietHsCmd (HsCmdApp _ _) = True
1285 isQuietHsCmd _ = False
1286
1287 -----------------------
1288 ppr_lcmd :: (SourceTextX p, OutputableBndrId p) => LHsCmd p -> SDoc
1289 ppr_lcmd c = ppr_cmd (unLoc c)
1290
1291 ppr_cmd :: forall p. (SourceTextX p, OutputableBndrId p) => HsCmd p -> SDoc
1292 ppr_cmd (HsCmdPar c) = parens (ppr_lcmd c)
1293
1294 ppr_cmd (HsCmdApp c e)
1295 = let (fun, args) = collect_args c [e] in
1296 hang (ppr_lcmd fun) 2 (sep (map ppr args))
1297 where
1298 collect_args (L _ (HsCmdApp fun arg)) args = collect_args fun (arg:args)
1299 collect_args fun args = (fun, args)
1300
1301 ppr_cmd (HsCmdLam matches)
1302 = pprMatches matches
1303
1304 ppr_cmd (HsCmdCase expr matches)
1305 = sep [ sep [text "case", nest 4 (ppr expr), ptext (sLit "of")],
1306 nest 2 (pprMatches matches) ]
1307
1308 ppr_cmd (HsCmdIf _ e ct ce)
1309 = sep [hsep [text "if", nest 2 (ppr e), ptext (sLit "then")],
1310 nest 4 (ppr ct),
1311 text "else",
1312 nest 4 (ppr ce)]
1313
1314 -- special case: let ... in let ...
1315 ppr_cmd (HsCmdLet (L _ binds) cmd@(L _ (HsCmdLet _ _)))
1316 = sep [hang (text "let") 2 (hsep [pprBinds binds, ptext (sLit "in")]),
1317 ppr_lcmd cmd]
1318
1319 ppr_cmd (HsCmdLet (L _ binds) cmd)
1320 = sep [hang (text "let") 2 (pprBinds binds),
1321 hang (text "in") 2 (ppr cmd)]
1322
1323 ppr_cmd (HsCmdDo (L _ stmts) _) = pprDo ArrowExpr stmts
1324
1325 ppr_cmd (HsCmdWrap w cmd)
1326 = pprHsWrapper w (\_ -> parens (ppr_cmd cmd))
1327 ppr_cmd (HsCmdArrApp arrow arg _ HsFirstOrderApp True)
1328 = hsep [ppr_lexpr arrow, larrowt, ppr_lexpr arg]
1329 ppr_cmd (HsCmdArrApp arrow arg _ HsFirstOrderApp False)
1330 = hsep [ppr_lexpr arg, arrowt, ppr_lexpr arrow]
1331 ppr_cmd (HsCmdArrApp arrow arg _ HsHigherOrderApp True)
1332 = hsep [ppr_lexpr arrow, larrowtt, ppr_lexpr arg]
1333 ppr_cmd (HsCmdArrApp arrow arg _ HsHigherOrderApp False)
1334 = hsep [ppr_lexpr arg, arrowtt, ppr_lexpr arrow]
1335
1336 ppr_cmd (HsCmdArrForm (L _ (HsVar (L _ v))) _ (Just _) [arg1, arg2])
1337 = hang (pprCmdArg (unLoc arg1)) 4 (sep [ pprInfixOcc v
1338 , pprCmdArg (unLoc arg2)])
1339 ppr_cmd (HsCmdArrForm (L _ (HsVar (L _ v))) Infix _ [arg1, arg2])
1340 = hang (pprCmdArg (unLoc arg1)) 4 (sep [ pprInfixOcc v
1341 , pprCmdArg (unLoc arg2)])
1342 ppr_cmd (HsCmdArrForm (L _ (HsConLikeOut c)) _ (Just _) [arg1, arg2])
1343 = hang (pprCmdArg (unLoc arg1)) 4 (sep [ pprInfixOcc (conLikeName c)
1344 , pprCmdArg (unLoc arg2)])
1345 ppr_cmd (HsCmdArrForm (L _ (HsConLikeOut c)) Infix _ [arg1, arg2])
1346 = hang (pprCmdArg (unLoc arg1)) 4 (sep [ pprInfixOcc (conLikeName c)
1347 , pprCmdArg (unLoc arg2)])
1348 ppr_cmd (HsCmdArrForm op _ _ args)
1349 = hang (text "(|" <> ppr_lexpr op)
1350 4 (sep (map (pprCmdArg.unLoc) args) <> text "|)")
1351
1352 pprCmdArg :: (SourceTextX p, OutputableBndrId p) => HsCmdTop p -> SDoc
1353 pprCmdArg (HsCmdTop cmd _ _ _)
1354 = ppr_lcmd cmd
1355
1356 instance (SourceTextX p, OutputableBndrId p) => Outputable (HsCmdTop p) where
1357 ppr = pprCmdArg
1358
1359 {-
1360 ************************************************************************
1361 * *
1362 \subsection{Record binds}
1363 * *
1364 ************************************************************************
1365 -}
1366
1367 -- | Haskell Record Bindings
1368 type HsRecordBinds p = HsRecFields p (LHsExpr p)
1369
1370 {-
1371 ************************************************************************
1372 * *
1373 \subsection{@Match@, @GRHSs@, and @GRHS@ datatypes}
1374 * *
1375 ************************************************************************
1376
1377 @Match@es are sets of pattern bindings and right hand sides for
1378 functions, patterns or case branches. For example, if a function @g@
1379 is defined as:
1380 \begin{verbatim}
1381 g (x,y) = y
1382 g ((x:ys),y) = y+1,
1383 \end{verbatim}
1384 then \tr{g} has two @Match@es: @(x,y) = y@ and @((x:ys),y) = y+1@.
1385
1386 It is always the case that each element of an @[Match]@ list has the
1387 same number of @pats@s inside it. This corresponds to saying that
1388 a function defined by pattern matching must have the same number of
1389 patterns in each equation.
1390 -}
1391
1392 data MatchGroup p body
1393 = MG { mg_alts :: Located [LMatch p body] -- The alternatives
1394 , mg_arg_tys :: [PostTc p Type] -- Types of the arguments, t1..tn
1395 , mg_res_ty :: PostTc p Type -- Type of the result, tr
1396 , mg_origin :: Origin }
1397 -- The type is the type of the entire group
1398 -- t1 -> ... -> tn -> tr
1399 -- where there are n patterns
1400 deriving instance (Data body,DataId p) => Data (MatchGroup p body)
1401
1402 -- | Located Match
1403 type LMatch id body = Located (Match id body)
1404 -- ^ May have 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnSemi' when in a
1405 -- list
1406
1407 -- For details on above see note [Api annotations] in ApiAnnotation
1408 data Match p body
1409 = Match {
1410 m_ctxt :: HsMatchContext (NameOrRdrName (IdP p)),
1411 -- See note [m_ctxt in Match]
1412 m_pats :: [LPat p], -- The patterns
1413 m_type :: (Maybe (LHsType p)),
1414 -- A type signature for the result of the match
1415 -- Nothing after typechecking
1416 -- NB: No longer supported
1417 m_grhss :: (GRHSs p body)
1418 }
1419 deriving instance (Data body,DataId p) => Data (Match p body)
1420
1421 instance (SourceTextX idR, OutputableBndrId idR, Outputable body)
1422 => Outputable (Match idR body) where
1423 ppr = pprMatch
1424
1425 {-
1426 Note [m_ctxt in Match]
1427 ~~~~~~~~~~~~~~~~~~~~~~
1428
1429 A Match can occur in a number of contexts, such as a FunBind, HsCase, HsLam and
1430 so on.
1431
1432 In order to simplify tooling processing and pretty print output, the provenance
1433 is captured in an HsMatchContext.
1434
1435 This is particularly important for the API Annotations for a multi-equation
1436 FunBind.
1437
1438 The parser initially creates a FunBind with a single Match in it for
1439 every function definition it sees.
1440
1441 These are then grouped together by getMonoBind into a single FunBind,
1442 where all the Matches are combined.
1443
1444 In the process, all the original FunBind fun_id's bar one are
1445 discarded, including the locations.
1446
1447 This causes a problem for source to source conversions via API
1448 Annotations, so the original fun_ids and infix flags are preserved in
1449 the Match, when it originates from a FunBind.
1450
1451 Example infix function definition requiring individual API Annotations
1452
1453 (&&& ) [] [] = []
1454 xs &&& [] = xs
1455 ( &&& ) [] ys = ys
1456
1457
1458
1459 -}
1460
1461
1462 isInfixMatch :: Match id body -> Bool
1463 isInfixMatch match = case m_ctxt match of
1464 FunRhs {mc_fixity = Infix} -> True
1465 _ -> False
1466
1467 isEmptyMatchGroup :: MatchGroup id body -> Bool
1468 isEmptyMatchGroup (MG { mg_alts = ms }) = null $ unLoc ms
1469
1470 -- | Is there only one RHS in this list of matches?
1471 isSingletonMatchGroup :: [LMatch id body] -> Bool
1472 isSingletonMatchGroup matches
1473 | [L _ match] <- matches
1474 , Match { m_grhss = GRHSs { grhssGRHSs = [_] } } <- match
1475 = True
1476 | otherwise
1477 = False
1478
1479 matchGroupArity :: MatchGroup id body -> Arity
1480 -- Precondition: MatchGroup is non-empty
1481 -- This is called before type checking, when mg_arg_tys is not set
1482 matchGroupArity (MG { mg_alts = alts })
1483 | L _ (alt1:_) <- alts = length (hsLMatchPats alt1)
1484 | otherwise = panic "matchGroupArity"
1485
1486 hsLMatchPats :: LMatch id body -> [LPat id]
1487 hsLMatchPats (L _ (Match _ pats _ _)) = pats
1488
1489 -- | Guarded Right-Hand Sides
1490 --
1491 -- GRHSs are used both for pattern bindings and for Matches
1492 --
1493 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnVbar',
1494 -- 'ApiAnnotation.AnnEqual','ApiAnnotation.AnnWhere',
1495 -- 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose'
1496 -- 'ApiAnnotation.AnnRarrow','ApiAnnotation.AnnSemi'
1497
1498 -- For details on above see note [Api annotations] in ApiAnnotation
1499 data GRHSs p body
1500 = GRHSs {
1501 grhssGRHSs :: [LGRHS p body], -- ^ Guarded RHSs
1502 grhssLocalBinds :: LHsLocalBinds p -- ^ The where clause
1503 }
1504 deriving instance (Data body,DataId p) => Data (GRHSs p body)
1505
1506 -- | Located Guarded Right-Hand Side
1507 type LGRHS id body = Located (GRHS id body)
1508
1509 -- | Guarded Right Hand Side.
1510 data GRHS id body = GRHS [GuardLStmt id] -- Guards
1511 body -- Right hand side
1512 deriving instance (Data body,DataId id) => Data (GRHS id body)
1513
1514 -- We know the list must have at least one @Match@ in it.
1515
1516 pprMatches :: (SourceTextX idR, OutputableBndrId idR, Outputable body)
1517 => MatchGroup idR body -> SDoc
1518 pprMatches MG { mg_alts = matches }
1519 = vcat (map pprMatch (map unLoc (unLoc matches)))
1520 -- Don't print the type; it's only a place-holder before typechecking
1521
1522 -- Exported to HsBinds, which can't see the defn of HsMatchContext
1523 pprFunBind :: (SourceTextX idR, OutputableBndrId idR, Outputable body)
1524 => MatchGroup idR body -> SDoc
1525 pprFunBind matches = pprMatches matches
1526
1527 -- Exported to HsBinds, which can't see the defn of HsMatchContext
1528 pprPatBind :: forall bndr p body. (SourceTextX p, SourceTextX bndr,
1529 OutputableBndrId bndr,
1530 OutputableBndrId p,
1531 Outputable body)
1532 => LPat bndr -> GRHSs p body -> SDoc
1533 pprPatBind pat (grhss)
1534 = sep [ppr pat, nest 2 (pprGRHSs (PatBindRhs :: HsMatchContext (IdP p)) grhss)]
1535
1536 pprMatch :: (SourceTextX idR, OutputableBndrId idR, Outputable body)
1537 => Match idR body -> SDoc
1538 pprMatch match
1539 = sep [ sep (herald : map (nest 2 . pprParendLPat) other_pats)
1540 , nest 2 ppr_maybe_ty
1541 , nest 2 (pprGRHSs ctxt (m_grhss match)) ]
1542 where
1543 ctxt = m_ctxt match
1544 (herald, other_pats)
1545 = case ctxt of
1546 FunRhs {mc_fun=L _ fun, mc_fixity=fixity, mc_strictness=strictness}
1547 | strictness == SrcStrict -> ASSERT(null $ m_pats match)
1548 (char '!'<>pprPrefixOcc fun, m_pats match)
1549 -- a strict variable binding
1550 | fixity == Prefix -> (pprPrefixOcc fun, m_pats match)
1551 -- f x y z = e
1552 -- Not pprBndr; the AbsBinds will
1553 -- have printed the signature
1554
1555 | null pats2 -> (pp_infix, [])
1556 -- x &&& y = e
1557
1558 | otherwise -> (parens pp_infix, pats2)
1559 -- (x &&& y) z = e
1560 where
1561 pp_infix = pprParendLPat pat1 <+> pprInfixOcc fun <+> pprParendLPat pat2
1562
1563 LambdaExpr -> (char '\\', m_pats match)
1564
1565 _ -> ASSERT2( null pats1, ppr ctxt $$ ppr pat1 $$ ppr pats1 )
1566 (ppr pat1, []) -- No parens around the single pat
1567
1568 (pat1:pats1) = m_pats match
1569 (pat2:pats2) = pats1
1570 ppr_maybe_ty = case m_type match of
1571 Just ty -> dcolon <+> ppr ty
1572 Nothing -> empty
1573
1574
1575 pprGRHSs :: (SourceTextX idR, OutputableBndrId idR, Outputable body)
1576 => HsMatchContext idL -> GRHSs idR body -> SDoc
1577 pprGRHSs ctxt (GRHSs grhss (L _ binds))
1578 = vcat (map (pprGRHS ctxt . unLoc) grhss)
1579 -- Print the "where" even if the contents of the binds is empty. Only
1580 -- EmptyLocalBinds means no "where" keyword
1581 $$ ppUnless (eqEmptyLocalBinds binds)
1582 (text "where" $$ nest 4 (pprBinds binds))
1583
1584 pprGRHS :: (SourceTextX idR, OutputableBndrId idR, Outputable body)
1585 => HsMatchContext idL -> GRHS idR body -> SDoc
1586 pprGRHS ctxt (GRHS [] body)
1587 = pp_rhs ctxt body
1588
1589 pprGRHS ctxt (GRHS guards body)
1590 = sep [vbar <+> interpp'SP guards, pp_rhs ctxt body]
1591
1592 pp_rhs :: Outputable body => HsMatchContext idL -> body -> SDoc
1593 pp_rhs ctxt rhs = matchSeparator ctxt <+> pprDeeper (ppr rhs)
1594
1595 {-
1596 ************************************************************************
1597 * *
1598 \subsection{Do stmts and list comprehensions}
1599 * *
1600 ************************************************************************
1601 -}
1602
1603 -- | Located @do@ block Statement
1604 type LStmt id body = Located (StmtLR id id body)
1605
1606 -- | Located Statement with separate Left and Right id's
1607 type LStmtLR idL idR body = Located (StmtLR idL idR body)
1608
1609 -- | @do@ block Statement
1610 type Stmt id body = StmtLR id id body
1611
1612 -- | Command Located Statement
1613 type CmdLStmt id = LStmt id (LHsCmd id)
1614
1615 -- | Command Statement
1616 type CmdStmt id = Stmt id (LHsCmd id)
1617
1618 -- | Expression Located Statement
1619 type ExprLStmt id = LStmt id (LHsExpr id)
1620
1621 -- | Expression Statement
1622 type ExprStmt id = Stmt id (LHsExpr id)
1623
1624 -- | Guard Located Statement
1625 type GuardLStmt id = LStmt id (LHsExpr id)
1626
1627 -- | Guard Statement
1628 type GuardStmt id = Stmt id (LHsExpr id)
1629
1630 -- | Ghci Located Statement
1631 type GhciLStmt id = LStmt id (LHsExpr id)
1632
1633 -- | Ghci Statement
1634 type GhciStmt id = Stmt id (LHsExpr id)
1635
1636 -- The SyntaxExprs in here are used *only* for do-notation and monad
1637 -- comprehensions, which have rebindable syntax. Otherwise they are unused.
1638 -- | API Annotations when in qualifier lists or guards
1639 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnVbar',
1640 -- 'ApiAnnotation.AnnComma','ApiAnnotation.AnnThen',
1641 -- 'ApiAnnotation.AnnBy','ApiAnnotation.AnnBy',
1642 -- 'ApiAnnotation.AnnGroup','ApiAnnotation.AnnUsing'
1643
1644 -- For details on above see note [Api annotations] in ApiAnnotation
1645 data StmtLR idL idR body -- body should always be (LHs**** idR)
1646 = LastStmt -- Always the last Stmt in ListComp, MonadComp, PArrComp,
1647 -- and (after the renamer) DoExpr, MDoExpr
1648 -- Not used for GhciStmtCtxt, PatGuard, which scope over other stuff
1649 body
1650 Bool -- True <=> return was stripped by ApplicativeDo
1651 (SyntaxExpr idR) -- The return operator, used only for
1652 -- MonadComp For ListComp, PArrComp, we
1653 -- use the baked-in 'return' For DoExpr,
1654 -- MDoExpr, we don't apply a 'return' at
1655 -- all See Note [Monad Comprehensions] |
1656 -- - 'ApiAnnotation.AnnKeywordId' :
1657 -- 'ApiAnnotation.AnnLarrow'
1658
1659 -- For details on above see note [Api annotations] in ApiAnnotation
1660 | BindStmt (LPat idL)
1661 body
1662 (SyntaxExpr idR) -- The (>>=) operator; see Note [The type of bind in Stmts]
1663 (SyntaxExpr idR) -- The fail operator
1664 -- The fail operator is noSyntaxExpr
1665 -- if the pattern match can't fail
1666
1667 (PostTc idR Type) -- result type of the function passed to bind;
1668 -- that is, S in (>>=) :: Q -> (R -> S) -> T
1669
1670 -- | 'ApplicativeStmt' represents an applicative expression built with
1671 -- <$> and <*>. It is generated by the renamer, and is desugared into the
1672 -- appropriate applicative expression by the desugarer, but it is intended
1673 -- to be invisible in error messages.
1674 --
1675 -- For full details, see Note [ApplicativeDo] in RnExpr
1676 --
1677 | ApplicativeStmt
1678 [ ( SyntaxExpr idR
1679 , ApplicativeArg idL idR) ]
1680 -- [(<$>, e1), (<*>, e2), ..., (<*>, en)]
1681 (Maybe (SyntaxExpr idR)) -- 'join', if necessary
1682 (PostTc idR Type) -- Type of the body
1683
1684 | BodyStmt body -- See Note [BodyStmt]
1685 (SyntaxExpr idR) -- The (>>) operator
1686 (SyntaxExpr idR) -- The `guard` operator; used only in MonadComp
1687 -- See notes [Monad Comprehensions]
1688 (PostTc idR Type) -- Element type of the RHS (used for arrows)
1689
1690 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLet'
1691 -- 'ApiAnnotation.AnnOpen' @'{'@,'ApiAnnotation.AnnClose' @'}'@,
1692
1693 -- For details on above see note [Api annotations] in ApiAnnotation
1694 | LetStmt (LHsLocalBindsLR idL idR)
1695
1696 -- ParStmts only occur in a list/monad comprehension
1697 | ParStmt [ParStmtBlock idL idR]
1698 (HsExpr idR) -- Polymorphic `mzip` for monad comprehensions
1699 (SyntaxExpr idR) -- The `>>=` operator
1700 -- See notes [Monad Comprehensions]
1701 (PostTc idR Type) -- S in (>>=) :: Q -> (R -> S) -> T
1702 -- After renaming, the ids are the binders
1703 -- bound by the stmts and used after themp
1704
1705 | TransStmt {
1706 trS_form :: TransForm,
1707 trS_stmts :: [ExprLStmt idL], -- Stmts to the *left* of the 'group'
1708 -- which generates the tuples to be grouped
1709
1710 trS_bndrs :: [(IdP idR, IdP idR)], -- See Note [TransStmt binder map]
1711
1712 trS_using :: LHsExpr idR,
1713 trS_by :: Maybe (LHsExpr idR), -- "by e" (optional)
1714 -- Invariant: if trS_form = GroupBy, then grp_by = Just e
1715
1716 trS_ret :: SyntaxExpr idR, -- The monomorphic 'return' function for
1717 -- the inner monad comprehensions
1718 trS_bind :: SyntaxExpr idR, -- The '(>>=)' operator
1719 trS_bind_arg_ty :: PostTc idR Type, -- R in (>>=) :: Q -> (R -> S) -> T
1720 trS_fmap :: HsExpr idR -- The polymorphic 'fmap' function for desugaring
1721 -- Only for 'group' forms
1722 -- Just a simple HsExpr, because it's
1723 -- too polymorphic for tcSyntaxOp
1724 } -- See Note [Monad Comprehensions]
1725
1726 -- Recursive statement (see Note [How RecStmt works] below)
1727 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnRec'
1728
1729 -- For details on above see note [Api annotations] in ApiAnnotation
1730 | RecStmt
1731 { recS_stmts :: [LStmtLR idL idR body]
1732
1733 -- The next two fields are only valid after renaming
1734 , recS_later_ids :: [IdP idR]
1735 -- The ids are a subset of the variables bound by the
1736 -- stmts that are used in stmts that follow the RecStmt
1737
1738 , recS_rec_ids :: [IdP idR]
1739 -- Ditto, but these variables are the "recursive" ones,
1740 -- that are used before they are bound in the stmts of
1741 -- the RecStmt.
1742 -- An Id can be in both groups
1743 -- Both sets of Ids are (now) treated monomorphically
1744 -- See Note [How RecStmt works] for why they are separate
1745
1746 -- Rebindable syntax
1747 , recS_bind_fn :: SyntaxExpr idR -- The bind function
1748 , recS_ret_fn :: SyntaxExpr idR -- The return function
1749 , recS_mfix_fn :: SyntaxExpr idR -- The mfix function
1750 , recS_bind_ty :: PostTc idR Type -- S in (>>=) :: Q -> (R -> S) -> T
1751
1752 -- These fields are only valid after typechecking
1753 , recS_later_rets :: [PostTcExpr] -- (only used in the arrow version)
1754 , recS_rec_rets :: [PostTcExpr] -- These expressions correspond 1-to-1
1755 -- with recS_later_ids and recS_rec_ids,
1756 -- and are the expressions that should be
1757 -- returned by the recursion.
1758 -- They may not quite be the Ids themselves,
1759 -- because the Id may be *polymorphic*, but
1760 -- the returned thing has to be *monomorphic*,
1761 -- so they may be type applications
1762
1763 , recS_ret_ty :: PostTc idR Type -- The type of
1764 -- do { stmts; return (a,b,c) }
1765 -- With rebindable syntax the type might not
1766 -- be quite as simple as (m (tya, tyb, tyc)).
1767 }
1768 deriving instance (Data body, DataId idL, DataId idR)
1769 => Data (StmtLR idL idR body)
1770
1771 data TransForm -- The 'f' below is the 'using' function, 'e' is the by function
1772 = ThenForm -- then f or then f by e (depending on trS_by)
1773 | GroupForm -- then group using f or then group by e using f (depending on trS_by)
1774 deriving Data
1775
1776 -- | Parenthesised Statement Block
1777 data ParStmtBlock idL idR
1778 = ParStmtBlock
1779 [ExprLStmt idL]
1780 [IdP idR] -- The variables to be returned
1781 (SyntaxExpr idR) -- The return operator
1782 deriving instance (DataId idL, DataId idR) => Data (ParStmtBlock idL idR)
1783
1784 -- | Applicative Argument
1785 data ApplicativeArg idL idR
1786 = ApplicativeArgOne -- pat <- expr (pat must be irrefutable)
1787 (LPat idL)
1788 (LHsExpr idL)
1789 | ApplicativeArgMany -- do { stmts; return vars }
1790 [ExprLStmt idL] -- stmts
1791 (HsExpr idL) -- return (v1,..,vn), or just (v1,..,vn)
1792 (LPat idL) -- (v1,...,vn)
1793 deriving instance (DataId idL, DataId idR) => Data (ApplicativeArg idL idR)
1794
1795 {-
1796 Note [The type of bind in Stmts]
1797 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1798 Some Stmts, notably BindStmt, keep the (>>=) bind operator.
1799 We do NOT assume that it has type
1800 (>>=) :: m a -> (a -> m b) -> m b
1801 In some cases (see Trac #303, #1537) it might have a more
1802 exotic type, such as
1803 (>>=) :: m i j a -> (a -> m j k b) -> m i k b
1804 So we must be careful not to make assumptions about the type.
1805 In particular, the monad may not be uniform throughout.
1806
1807 Note [TransStmt binder map]
1808 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1809 The [(idR,idR)] in a TransStmt behaves as follows:
1810
1811 * Before renaming: []
1812
1813 * After renaming:
1814 [ (x27,x27), ..., (z35,z35) ]
1815 These are the variables
1816 bound by the stmts to the left of the 'group'
1817 and used either in the 'by' clause,
1818 or in the stmts following the 'group'
1819 Each item is a pair of identical variables.
1820
1821 * After typechecking:
1822 [ (x27:Int, x27:[Int]), ..., (z35:Bool, z35:[Bool]) ]
1823 Each pair has the same unique, but different *types*.
1824
1825 Note [BodyStmt]
1826 ~~~~~~~~~~~~~~~
1827 BodyStmts are a bit tricky, because what they mean
1828 depends on the context. Consider the following contexts:
1829
1830 A do expression of type (m res_ty)
1831 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1832 * BodyStmt E any_ty: do { ....; E; ... }
1833 E :: m any_ty
1834 Translation: E >> ...
1835
1836 A list comprehensions of type [elt_ty]
1837 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1838 * BodyStmt E Bool: [ .. | .... E ]
1839 [ .. | ..., E, ... ]
1840 [ .. | .... | ..., E | ... ]
1841 E :: Bool
1842 Translation: if E then fail else ...
1843
1844 A guard list, guarding a RHS of type rhs_ty
1845 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1846 * BodyStmt E BooParStmtBlockl: f x | ..., E, ... = ...rhs...
1847 E :: Bool
1848 Translation: if E then fail else ...
1849
1850 A monad comprehension of type (m res_ty)
1851 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1852 * BodyStmt E Bool: [ .. | .... E ]
1853 E :: Bool
1854 Translation: guard E >> ...
1855
1856 Array comprehensions are handled like list comprehensions.
1857
1858 Note [How RecStmt works]
1859 ~~~~~~~~~~~~~~~~~~~~~~~~
1860 Example:
1861 HsDo [ BindStmt x ex
1862
1863 , RecStmt { recS_rec_ids = [a, c]
1864 , recS_stmts = [ BindStmt b (return (a,c))
1865 , LetStmt a = ...b...
1866 , BindStmt c ec ]
1867 , recS_later_ids = [a, b]
1868
1869 , return (a b) ]
1870
1871 Here, the RecStmt binds a,b,c; but
1872 - Only a,b are used in the stmts *following* the RecStmt,
1873 - Only a,c are used in the stmts *inside* the RecStmt
1874 *before* their bindings
1875
1876 Why do we need *both* rec_ids and later_ids? For monads they could be
1877 combined into a single set of variables, but not for arrows. That
1878 follows from the types of the respective feedback operators:
1879
1880 mfix :: MonadFix m => (a -> m a) -> m a
1881 loop :: ArrowLoop a => a (b,d) (c,d) -> a b c
1882
1883 * For mfix, the 'a' covers the union of the later_ids and the rec_ids
1884 * For 'loop', 'c' is the later_ids and 'd' is the rec_ids
1885
1886 Note [Typing a RecStmt]
1887 ~~~~~~~~~~~~~~~~~~~~~~~
1888 A (RecStmt stmts) types as if you had written
1889
1890 (v1,..,vn, _, ..., _) <- mfix (\~(_, ..., _, r1, ..., rm) ->
1891 do { stmts
1892 ; return (v1,..vn, r1, ..., rm) })
1893
1894 where v1..vn are the later_ids
1895 r1..rm are the rec_ids
1896
1897 Note [Monad Comprehensions]
1898 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1899 Monad comprehensions require separate functions like 'return' and
1900 '>>=' for desugaring. These functions are stored in the statements
1901 used in monad comprehensions. For example, the 'return' of the 'LastStmt'
1902 expression is used to lift the body of the monad comprehension:
1903
1904 [ body | stmts ]
1905 =>
1906 stmts >>= \bndrs -> return body
1907
1908 In transform and grouping statements ('then ..' and 'then group ..') the
1909 'return' function is required for nested monad comprehensions, for example:
1910
1911 [ body | stmts, then f, rest ]
1912 =>
1913 f [ env | stmts ] >>= \bndrs -> [ body | rest ]
1914
1915 BodyStmts require the 'Control.Monad.guard' function for boolean
1916 expressions:
1917
1918 [ body | exp, stmts ]
1919 =>
1920 guard exp >> [ body | stmts ]
1921
1922 Parallel statements require the 'Control.Monad.Zip.mzip' function:
1923
1924 [ body | stmts1 | stmts2 | .. ]
1925 =>
1926 mzip stmts1 (mzip stmts2 (..)) >>= \(bndrs1, (bndrs2, ..)) -> return body
1927
1928 In any other context than 'MonadComp', the fields for most of these
1929 'SyntaxExpr's stay bottom.
1930 -}
1931
1932 instance (SourceTextX idL, OutputableBndrId idL)
1933 => Outputable (ParStmtBlock idL idR) where
1934 ppr (ParStmtBlock stmts _ _) = interpp'SP stmts
1935
1936 instance (SourceTextX idL, SourceTextX idR,
1937 OutputableBndrId idL, OutputableBndrId idR, Outputable body)
1938 => Outputable (StmtLR idL idR body) where
1939 ppr stmt = pprStmt stmt
1940
1941 pprStmt :: forall idL idR body . (SourceTextX idL, SourceTextX idR,
1942 OutputableBndrId idL, OutputableBndrId idR,
1943 Outputable body)
1944 => (StmtLR idL idR body) -> SDoc
1945 pprStmt (LastStmt expr ret_stripped _)
1946 = ifPprDebug (text "[last]") <+>
1947 (if ret_stripped then text "return" else empty) <+>
1948 ppr expr
1949 pprStmt (BindStmt pat expr _ _ _) = hsep [ppr pat, larrow, ppr expr]
1950 pprStmt (LetStmt (L _ binds)) = hsep [text "let", pprBinds binds]
1951 pprStmt (BodyStmt expr _ _ _) = ppr expr
1952 pprStmt (ParStmt stmtss _ _ _) = sep (punctuate (text " | ") (map ppr stmtss))
1953
1954 pprStmt (TransStmt { trS_stmts = stmts, trS_by = by, trS_using = using, trS_form = form })
1955 = sep $ punctuate comma (map ppr stmts ++ [pprTransStmt by using form])
1956
1957 pprStmt (RecStmt { recS_stmts = segment, recS_rec_ids = rec_ids
1958 , recS_later_ids = later_ids })
1959 = text "rec" <+>
1960 vcat [ ppr_do_stmts segment
1961 , ifPprDebug (vcat [ text "rec_ids=" <> ppr rec_ids
1962 , text "later_ids=" <> ppr later_ids])]
1963
1964 pprStmt (ApplicativeStmt args mb_join _)
1965 = getPprStyle $ \style ->
1966 if userStyle style
1967 then pp_for_user
1968 else pp_debug
1969 where
1970 -- make all the Applicative stuff invisible in error messages by
1971 -- flattening the whole ApplicativeStmt nest back to a sequence
1972 -- of statements.
1973 pp_for_user = vcat $ concatMap flattenArg args
1974
1975 -- ppr directly rather than transforming here, because we need to
1976 -- inject a "return" which is hard when we're polymorphic in the id
1977 -- type.
1978 flattenStmt :: ExprLStmt idL -> [SDoc]
1979 flattenStmt (L _ (ApplicativeStmt args _ _)) = concatMap flattenArg args
1980 flattenStmt stmt = [ppr stmt]
1981
1982 flattenArg (_, ApplicativeArgOne pat expr) =
1983 [ppr (BindStmt pat expr noSyntaxExpr noSyntaxExpr (panic "pprStmt")
1984 :: ExprStmt idL)]
1985 flattenArg (_, ApplicativeArgMany stmts _ _) =
1986 concatMap flattenStmt stmts
1987
1988 pp_debug =
1989 let
1990 ap_expr = sep (punctuate (text " |") (map pp_arg args))
1991 in
1992 if isNothing mb_join
1993 then ap_expr
1994 else text "join" <+> parens ap_expr
1995
1996 pp_arg (_, ApplicativeArgOne pat expr) =
1997 ppr (BindStmt pat expr noSyntaxExpr noSyntaxExpr (panic "pprStmt")
1998 :: ExprStmt idL)
1999 pp_arg (_, ApplicativeArgMany stmts return pat) =
2000 ppr pat <+>
2001 text "<-" <+>
2002 ppr (HsDo DoExpr (noLoc
2003 (stmts ++ [noLoc (LastStmt (noLoc return) False noSyntaxExpr)]))
2004 (error "pprStmt"))
2005
2006 pprTransformStmt :: (SourceTextX p, OutputableBndrId p)
2007 => [IdP p] -> LHsExpr p -> Maybe (LHsExpr p) -> SDoc
2008 pprTransformStmt bndrs using by
2009 = sep [ text "then" <+> ifPprDebug (braces (ppr bndrs))
2010 , nest 2 (ppr using)
2011 , nest 2 (pprBy by)]
2012
2013 pprTransStmt :: Outputable body => Maybe body -> body -> TransForm -> SDoc
2014 pprTransStmt by using ThenForm
2015 = sep [ text "then", nest 2 (ppr using), nest 2 (pprBy by)]
2016 pprTransStmt by using GroupForm
2017 = sep [ text "then group", nest 2 (pprBy by), nest 2 (ptext (sLit "using") <+> ppr using)]
2018
2019 pprBy :: Outputable body => Maybe body -> SDoc
2020 pprBy Nothing = empty
2021 pprBy (Just e) = text "by" <+> ppr e
2022
2023 pprDo :: (SourceTextX p, OutputableBndrId p, Outputable body)
2024 => HsStmtContext any -> [LStmt p body] -> SDoc
2025 pprDo DoExpr stmts = text "do" <+> ppr_do_stmts stmts
2026 pprDo GhciStmtCtxt stmts = text "do" <+> ppr_do_stmts stmts
2027 pprDo ArrowExpr stmts = text "do" <+> ppr_do_stmts stmts
2028 pprDo MDoExpr stmts = text "mdo" <+> ppr_do_stmts stmts
2029 pprDo ListComp stmts = brackets $ pprComp stmts
2030 pprDo PArrComp stmts = paBrackets $ pprComp stmts
2031 pprDo MonadComp stmts = brackets $ pprComp stmts
2032 pprDo _ _ = panic "pprDo" -- PatGuard, ParStmtCxt
2033
2034 ppr_do_stmts :: (SourceTextX idL, SourceTextX idR,
2035 OutputableBndrId idL, OutputableBndrId idR, Outputable body)
2036 => [LStmtLR idL idR body] -> SDoc
2037 -- Print a bunch of do stmts
2038 ppr_do_stmts stmts = pprDeeperList vcat (map ppr stmts)
2039
2040 pprComp :: (SourceTextX p, OutputableBndrId p, Outputable body)
2041 => [LStmt p body] -> SDoc
2042 pprComp quals -- Prints: body | qual1, ..., qualn
2043 | Just (initStmts, L _ (LastStmt body _ _)) <- snocView quals
2044 = if null initStmts
2045 -- If there are no statements in a list comprehension besides the last
2046 -- one, we simply treat it like a normal list. This does arise
2047 -- occasionally in code that GHC generates, e.g., in implementations of
2048 -- 'range' for derived 'Ix' instances for product datatypes with exactly
2049 -- one constructor (e.g., see Trac #12583).
2050 then ppr body
2051 else hang (ppr body <+> vbar) 2 (pprQuals initStmts)
2052 | otherwise
2053 = pprPanic "pprComp" (pprQuals quals)
2054
2055 pprQuals :: (SourceTextX p, OutputableBndrId p, Outputable body)
2056 => [LStmt p body] -> SDoc
2057 -- Show list comprehension qualifiers separated by commas
2058 pprQuals quals = interpp'SP quals
2059
2060 {-
2061 ************************************************************************
2062 * *
2063 Template Haskell quotation brackets
2064 * *
2065 ************************************************************************
2066 -}
2067
2068 -- | Haskell Splice
2069 data HsSplice id
2070 = HsTypedSplice -- $$z or $$(f 4)
2071 SpliceDecoration -- Whether $$( ) variant found, for pretty printing
2072 (IdP id) -- A unique name to identify this splice point
2073 (LHsExpr id) -- See Note [Pending Splices]
2074
2075 | HsUntypedSplice -- $z or $(f 4)
2076 SpliceDecoration -- Whether $( ) variant found, for pretty printing
2077 (IdP id) -- A unique name to identify this splice point
2078 (LHsExpr id) -- See Note [Pending Splices]
2079
2080 | HsQuasiQuote -- See Note [Quasi-quote overview] in TcSplice
2081 (IdP id) -- Splice point
2082 (IdP id) -- Quoter
2083 SrcSpan -- The span of the enclosed string
2084 FastString -- The enclosed string
2085
2086 | HsSpliced -- See Note [Delaying modFinalizers in untyped splices] in
2087 -- RnSplice.
2088 -- This is the result of splicing a splice. It is produced by
2089 -- the renamer and consumed by the typechecker. It lives only
2090 -- between the two.
2091 ThModFinalizers -- TH finalizers produced by the splice.
2092 (HsSplicedThing id) -- The result of splicing
2093 deriving Typeable
2094 deriving instance (DataId id) => Data (HsSplice id)
2095
2096 -- | A splice can appear with various decorations wrapped around it. This data
2097 -- type captures explicitly how it was originally written, for use in the pretty
2098 -- printer.
2099 data SpliceDecoration
2100 = HasParens -- ^ $( splice ) or $$( splice )
2101 | HasDollar -- ^ $splice or $$splice
2102 | NoParens -- ^ bare splice
2103 deriving (Data, Eq, Show)
2104
2105 instance Outputable SpliceDecoration where
2106 ppr x = text $ show x
2107
2108
2109 isTypedSplice :: HsSplice id -> Bool
2110 isTypedSplice (HsTypedSplice {}) = True
2111 isTypedSplice _ = False -- Quasi-quotes are untyped splices
2112
2113 -- | Finalizers produced by a splice with
2114 -- 'Language.Haskell.TH.Syntax.addModFinalizer'
2115 --
2116 -- See Note [Delaying modFinalizers in untyped splices] in RnSplice. For how
2117 -- this is used.
2118 --
2119 newtype ThModFinalizers = ThModFinalizers [ForeignRef (TH.Q ())]
2120
2121 -- A Data instance which ignores the argument of 'ThModFinalizers'.
2122 instance Data ThModFinalizers where
2123 gunfold _ z _ = z $ ThModFinalizers []
2124 toConstr a = mkConstr (dataTypeOf a) "ThModFinalizers" [] Data.Prefix
2125 dataTypeOf a = mkDataType "HsExpr.ThModFinalizers" [toConstr a]
2126
2127 -- | Haskell Spliced Thing
2128 --
2129 -- Values that can result from running a splice.
2130 data HsSplicedThing id
2131 = HsSplicedExpr (HsExpr id) -- ^ Haskell Spliced Expression
2132 | HsSplicedTy (HsType id) -- ^ Haskell Spliced Type
2133 | HsSplicedPat (Pat id) -- ^ Haskell Spliced Pattern
2134 deriving Typeable
2135
2136 deriving instance (DataId id) => Data (HsSplicedThing id)
2137
2138 -- See Note [Pending Splices]
2139 type SplicePointName = Name
2140
2141 -- | Pending Renamer Splice
2142 data PendingRnSplice
2143 -- AZ:TODO: The hard-coded GhcRn feels wrong. How to force the PostRn?
2144 = PendingRnSplice UntypedSpliceFlavour SplicePointName (LHsExpr GhcRn)
2145 deriving Data
2146
2147 data UntypedSpliceFlavour
2148 = UntypedExpSplice
2149 | UntypedPatSplice
2150 | UntypedTypeSplice
2151 | UntypedDeclSplice
2152 deriving Data
2153
2154 -- | Pending Type-checker Splice
2155 data PendingTcSplice
2156 -- AZ:TODO: The hard-coded GhcTc feels wrong. How to force the PostTc?
2157 = PendingTcSplice SplicePointName (LHsExpr GhcTc)
2158 deriving Data
2159
2160
2161 {-
2162 Note [Pending Splices]
2163 ~~~~~~~~~~~~~~~~~~~~~~
2164 When we rename an untyped bracket, we name and lift out all the nested
2165 splices, so that when the typechecker hits the bracket, it can
2166 typecheck those nested splices without having to walk over the untyped
2167 bracket code. So for example
2168 [| f $(g x) |]
2169 looks like
2170
2171 HsBracket (HsApp (HsVar "f") (HsSpliceE _ (g x)))
2172
2173 which the renamer rewrites to
2174
2175 HsRnBracketOut (HsApp (HsVar f) (HsSpliceE sn (g x)))
2176 [PendingRnSplice UntypedExpSplice sn (g x)]
2177
2178 * The 'sn' is the Name of the splice point, the SplicePointName
2179
2180 * The PendingRnExpSplice gives the splice that splice-point name maps to;
2181 and the typechecker can now conveniently find these sub-expressions
2182
2183 * The other copy of the splice, in the second argument of HsSpliceE
2184 in the renamed first arg of HsRnBracketOut
2185 is used only for pretty printing
2186
2187 There are four varieties of pending splices generated by the renamer,
2188 distinguished by their UntypedSpliceFlavour
2189
2190 * Pending expression splices (UntypedExpSplice), e.g.,
2191 [|$(f x) + 2|]
2192
2193 UntypedExpSplice is also used for
2194 * quasi-quotes, where the pending expression expands to
2195 $(quoter "...blah...")
2196 (see RnSplice.makePending, HsQuasiQuote case)
2197
2198 * cross-stage lifting, where the pending expression expands to
2199 $(lift x)
2200 (see RnSplice.checkCrossStageLifting)
2201
2202 * Pending pattern splices (UntypedPatSplice), e.g.,
2203 [| \$(f x) -> x |]
2204
2205 * Pending type splices (UntypedTypeSplice), e.g.,
2206 [| f :: $(g x) |]
2207
2208 * Pending declaration (UntypedDeclSplice), e.g.,
2209 [| let $(f x) in ... |]
2210
2211 There is a fifth variety of pending splice, which is generated by the type
2212 checker:
2213
2214 * Pending *typed* expression splices, (PendingTcSplice), e.g.,
2215 [||1 + $$(f 2)||]
2216
2217 It would be possible to eliminate HsRnBracketOut and use HsBracketOut for the
2218 output of the renamer. However, when pretty printing the output of the renamer,
2219 e.g., in a type error message, we *do not* want to print out the pending
2220 splices. In contrast, when pretty printing the output of the type checker, we
2221 *do* want to print the pending splices. So splitting them up seems to make
2222 sense, although I hate to add another constructor to HsExpr.
2223 -}
2224
2225 instance (SourceTextX p, OutputableBndrId p)
2226 => Outputable (HsSplicedThing p) where
2227 ppr (HsSplicedExpr e) = ppr_expr e
2228 ppr (HsSplicedTy t) = ppr t
2229 ppr (HsSplicedPat p) = ppr p
2230
2231 instance (SourceTextX p, OutputableBndrId p) => Outputable (HsSplice p) where
2232 ppr s = pprSplice s
2233
2234 pprPendingSplice :: (SourceTextX p, OutputableBndrId p)
2235 => SplicePointName -> LHsExpr p -> SDoc
2236 pprPendingSplice n e = angleBrackets (ppr n <> comma <+> ppr e)
2237
2238 pprSpliceDecl :: (SourceTextX p, OutputableBndrId p)
2239 => HsSplice p -> SpliceExplicitFlag -> SDoc
2240 pprSpliceDecl e@HsQuasiQuote{} _ = pprSplice e
2241 pprSpliceDecl e ExplicitSplice = text "$(" <> ppr_splice_decl e <> text ")"
2242 pprSpliceDecl e ImplicitSplice = ppr_splice_decl e
2243
2244 ppr_splice_decl :: (SourceTextX p, OutputableBndrId p) => HsSplice p -> SDoc
2245 ppr_splice_decl (HsUntypedSplice _ n e) = ppr_splice empty n e empty
2246 ppr_splice_decl e = pprSplice e
2247
2248 pprSplice :: (SourceTextX p, OutputableBndrId p) => HsSplice p -> SDoc
2249 pprSplice (HsTypedSplice HasParens n e)
2250 = ppr_splice (text "$$(") n e (text ")")
2251 pprSplice (HsTypedSplice HasDollar n e)
2252 = ppr_splice (text "$$") n e empty
2253 pprSplice (HsTypedSplice NoParens n e)
2254 = ppr_splice empty n e empty
2255 pprSplice (HsUntypedSplice HasParens n e)
2256 = ppr_splice (text "$(") n e (text ")")
2257 pprSplice (HsUntypedSplice HasDollar n e)
2258 = ppr_splice (text "$") n e empty
2259 pprSplice (HsUntypedSplice NoParens n e)
2260 = ppr_splice empty n e empty
2261 pprSplice (HsQuasiQuote n q _ s) = ppr_quasi n q s
2262 pprSplice (HsSpliced _ thing) = ppr thing
2263
2264 ppr_quasi :: OutputableBndr p => p -> p -> FastString -> SDoc
2265 ppr_quasi n quoter quote = ifPprDebug (brackets (ppr n)) <>
2266 char '[' <> ppr quoter <> vbar <>
2267 ppr quote <> text "|]"
2268
2269 ppr_splice :: (SourceTextX p, OutputableBndrId p)
2270 => SDoc -> (IdP p) -> LHsExpr p -> SDoc -> SDoc
2271 ppr_splice herald n e trail
2272 = herald <> ifPprDebug (brackets (ppr n)) <> ppr e <> trail
2273
2274 -- | Haskell Bracket
2275 data HsBracket p = ExpBr (LHsExpr p) -- [| expr |]
2276 | PatBr (LPat p) -- [p| pat |]
2277 | DecBrL [LHsDecl p] -- [d| decls |]; result of parser
2278 | DecBrG (HsGroup p) -- [d| decls |]; result of renamer
2279 | TypBr (LHsType p) -- [t| type |]
2280 | VarBr Bool (IdP p) -- True: 'x, False: ''T
2281 -- (The Bool flag is used only in pprHsBracket)
2282 | TExpBr (LHsExpr p) -- [|| expr ||]
2283 deriving instance (DataId p) => Data (HsBracket p)
2284
2285 isTypedBracket :: HsBracket id -> Bool
2286 isTypedBracket (TExpBr {}) = True
2287 isTypedBracket _ = False
2288
2289 instance (SourceTextX p, OutputableBndrId p) => Outputable (HsBracket p) where
2290 ppr = pprHsBracket
2291
2292
2293 pprHsBracket :: (SourceTextX p, OutputableBndrId p) => HsBracket p -> SDoc
2294 pprHsBracket (ExpBr e) = thBrackets empty (ppr e)
2295 pprHsBracket (PatBr p) = thBrackets (char 'p') (ppr p)
2296 pprHsBracket (DecBrG gp) = thBrackets (char 'd') (ppr gp)
2297 pprHsBracket (DecBrL ds) = thBrackets (char 'd') (vcat (map ppr ds))
2298 pprHsBracket (TypBr t) = thBrackets (char 't') (ppr t)
2299 pprHsBracket (VarBr True n)
2300 = char '\'' <> pprPrefixOcc n
2301 pprHsBracket (VarBr False n)
2302 = text "''" <> pprPrefixOcc n
2303 pprHsBracket (TExpBr e) = thTyBrackets (ppr e)
2304
2305 thBrackets :: SDoc -> SDoc -> SDoc
2306 thBrackets pp_kind pp_body = char '[' <> pp_kind <> vbar <+>
2307 pp_body <+> text "|]"
2308
2309 thTyBrackets :: SDoc -> SDoc
2310 thTyBrackets pp_body = text "[||" <+> pp_body <+> ptext (sLit "||]")
2311
2312 instance Outputable PendingRnSplice where
2313 ppr (PendingRnSplice _ n e) = pprPendingSplice n e
2314
2315 instance Outputable PendingTcSplice where
2316 ppr (PendingTcSplice n e) = pprPendingSplice n e
2317
2318 {-
2319 ************************************************************************
2320 * *
2321 \subsection{Enumerations and list comprehensions}
2322 * *
2323 ************************************************************************
2324 -}
2325
2326 -- | Arithmetic Sequence Information
2327 data ArithSeqInfo id
2328 = From (LHsExpr id)
2329 | FromThen (LHsExpr id)
2330 (LHsExpr id)
2331 | FromTo (LHsExpr id)
2332 (LHsExpr id)
2333 | FromThenTo (LHsExpr id)
2334 (LHsExpr id)
2335 (LHsExpr id)
2336 deriving instance (DataId id) => Data (ArithSeqInfo id)
2337
2338 instance (SourceTextX p, OutputableBndrId p)
2339 => Outputable (ArithSeqInfo p) where
2340 ppr (From e1) = hcat [ppr e1, pp_dotdot]
2341 ppr (FromThen e1 e2) = hcat [ppr e1, comma, space, ppr e2, pp_dotdot]
2342 ppr (FromTo e1 e3) = hcat [ppr e1, pp_dotdot, ppr e3]
2343 ppr (FromThenTo e1 e2 e3)
2344 = hcat [ppr e1, comma, space, ppr e2, pp_dotdot, ppr e3]
2345
2346 pp_dotdot :: SDoc
2347 pp_dotdot = text " .. "
2348
2349 {-
2350 ************************************************************************
2351 * *
2352 \subsection{HsMatchCtxt}
2353 * *
2354 ************************************************************************
2355 -}
2356
2357 -- | Haskell Match Context
2358 --
2359 -- Context of a pattern match. This is more subtle than it would seem. See Note
2360 -- [Varieties of pattern matches].
2361 data HsMatchContext id -- Not an extensible tag
2362 = FunRhs { mc_fun :: Located id -- ^ function binder of @f@
2363 , mc_fixity :: LexicalFixity -- ^ fixing of @f@
2364 , mc_strictness :: SrcStrictness
2365 -- ^ was the pattern banged? See
2366 -- Note [Varieties of binding pattern matches]
2367 }
2368 -- ^A pattern matching on an argument of a
2369 -- function binding
2370 | LambdaExpr -- ^Patterns of a lambda
2371 | CaseAlt -- ^Patterns and guards on a case alternative
2372 | IfAlt -- ^Guards of a multi-way if alternative
2373 | ProcExpr -- ^Patterns of a proc
2374 | PatBindRhs -- ^A pattern binding eg [y] <- e = e
2375
2376 | RecUpd -- ^Record update [used only in DsExpr to
2377 -- tell matchWrapper what sort of
2378 -- runtime error message to generate]
2379
2380 | StmtCtxt (HsStmtContext id) -- ^Pattern of a do-stmt, list comprehension,
2381 -- pattern guard, etc
2382
2383 | ThPatSplice -- ^A Template Haskell pattern splice
2384 | ThPatQuote -- ^A Template Haskell pattern quotation [p| (a,b) |]
2385 | PatSyn -- ^A pattern synonym declaration
2386 deriving Functor
2387 deriving instance (Data id) => Data (HsMatchContext id)
2388
2389 instance OutputableBndr id => Outputable (HsMatchContext id) where
2390 ppr m@(FunRhs{}) = text "FunRhs" <+> ppr (mc_fun m) <+> ppr (mc_fixity m)
2391 ppr LambdaExpr = text "LambdaExpr"
2392 ppr CaseAlt = text "CaseAlt"
2393 ppr IfAlt = text "IfAlt"
2394 ppr ProcExpr = text "ProcExpr"
2395 ppr PatBindRhs = text "PatBindRhs"
2396 ppr RecUpd = text "RecUpd"
2397 ppr (StmtCtxt _) = text "StmtCtxt _"
2398 ppr ThPatSplice = text "ThPatSplice"
2399 ppr ThPatQuote = text "ThPatQuote"
2400 ppr PatSyn = text "PatSyn"
2401
2402 isPatSynCtxt :: HsMatchContext id -> Bool
2403 isPatSynCtxt ctxt =
2404 case ctxt of
2405 PatSyn -> True
2406 _ -> False
2407
2408 -- | Haskell Statement Context. It expects to be parameterised with one of
2409 -- 'RdrName', 'Name' or 'Id'
2410 data HsStmtContext id
2411 = ListComp
2412 | MonadComp
2413 | PArrComp -- ^Parallel array comprehension
2414
2415 | DoExpr -- ^do { ... }
2416 | MDoExpr -- ^mdo { ... } ie recursive do-expression
2417 | ArrowExpr -- ^do-notation in an arrow-command context
2418
2419 | GhciStmtCtxt -- ^A command-line Stmt in GHCi pat <- rhs
2420 | PatGuard (HsMatchContext id) -- ^Pattern guard for specified thing
2421 | ParStmtCtxt (HsStmtContext id) -- ^A branch of a parallel stmt
2422 | TransStmtCtxt (HsStmtContext id) -- ^A branch of a transform stmt
2423 deriving Functor
2424 deriving instance (Data id) => Data (HsStmtContext id)
2425
2426 isListCompExpr :: HsStmtContext id -> Bool
2427 -- Uses syntax [ e | quals ]
2428 isListCompExpr ListComp = True
2429 isListCompExpr PArrComp = True
2430 isListCompExpr MonadComp = True
2431 isListCompExpr (ParStmtCtxt c) = isListCompExpr c
2432 isListCompExpr (TransStmtCtxt c) = isListCompExpr c
2433 isListCompExpr _ = False
2434
2435 isMonadCompExpr :: HsStmtContext id -> Bool
2436 isMonadCompExpr MonadComp = True
2437 isMonadCompExpr (ParStmtCtxt ctxt) = isMonadCompExpr ctxt
2438 isMonadCompExpr (TransStmtCtxt ctxt) = isMonadCompExpr ctxt
2439 isMonadCompExpr _ = False
2440
2441 -- | Should pattern match failure in a 'HsStmtContext' be desugared using
2442 -- 'MonadFail'?
2443 isMonadFailStmtContext :: HsStmtContext id -> Bool
2444 isMonadFailStmtContext MonadComp = True
2445 isMonadFailStmtContext DoExpr = True
2446 isMonadFailStmtContext MDoExpr = True
2447 isMonadFailStmtContext GhciStmtCtxt = True
2448 isMonadFailStmtContext _ = False
2449
2450 matchSeparator :: HsMatchContext id -> SDoc
2451 matchSeparator (FunRhs {}) = text "="
2452 matchSeparator CaseAlt = text "->"
2453 matchSeparator IfAlt = text "->"
2454 matchSeparator LambdaExpr = text "->"
2455 matchSeparator ProcExpr = text "->"
2456 matchSeparator PatBindRhs = text "="
2457 matchSeparator (StmtCtxt _) = text "<-"
2458 matchSeparator RecUpd = text "=" -- This can be printed by the pattern
2459 -- match checker trace
2460 matchSeparator ThPatSplice = panic "unused"
2461 matchSeparator ThPatQuote = panic "unused"
2462 matchSeparator PatSyn = panic "unused"
2463
2464 pprMatchContext :: (Outputable (NameOrRdrName id),Outputable id)
2465 => HsMatchContext id -> SDoc
2466 pprMatchContext ctxt
2467 | want_an ctxt = text "an" <+> pprMatchContextNoun ctxt
2468 | otherwise = text "a" <+> pprMatchContextNoun ctxt
2469 where
2470 want_an (FunRhs {}) = True -- Use "an" in front
2471 want_an ProcExpr = True
2472 want_an _ = False
2473
2474 pprMatchContextNoun :: (Outputable (NameOrRdrName id),Outputable id)
2475 => HsMatchContext id -> SDoc
2476 pprMatchContextNoun (FunRhs {mc_fun=L _ fun})
2477 = text "equation for"
2478 <+> quotes (ppr fun)
2479 pprMatchContextNoun CaseAlt = text "case alternative"
2480 pprMatchContextNoun IfAlt = text "multi-way if alternative"
2481 pprMatchContextNoun RecUpd = text "record-update construct"
2482 pprMatchContextNoun ThPatSplice = text "Template Haskell pattern splice"
2483 pprMatchContextNoun ThPatQuote = text "Template Haskell pattern quotation"
2484 pprMatchContextNoun PatBindRhs = text "pattern binding"
2485 pprMatchContextNoun LambdaExpr = text "lambda abstraction"
2486 pprMatchContextNoun ProcExpr = text "arrow abstraction"
2487 pprMatchContextNoun (StmtCtxt ctxt) = text "pattern binding in"
2488 $$ pprStmtContext ctxt
2489 pprMatchContextNoun PatSyn = text "pattern synonym declaration"
2490
2491 -----------------
2492 pprAStmtContext, pprStmtContext :: (Outputable id,
2493 Outputable (NameOrRdrName id))
2494 => HsStmtContext id -> SDoc
2495 pprAStmtContext ctxt = article <+> pprStmtContext ctxt
2496 where
2497 pp_an = text "an"
2498 pp_a = text "a"
2499 article = case ctxt of
2500 MDoExpr -> pp_an
2501 PArrComp -> pp_an
2502 GhciStmtCtxt -> pp_an
2503 _ -> pp_a
2504
2505
2506 -----------------
2507 pprStmtContext GhciStmtCtxt = text "interactive GHCi command"
2508 pprStmtContext DoExpr = text "'do' block"
2509 pprStmtContext MDoExpr = text "'mdo' block"
2510 pprStmtContext ArrowExpr = text "'do' block in an arrow command"
2511 pprStmtContext ListComp = text "list comprehension"
2512 pprStmtContext MonadComp = text "monad comprehension"
2513 pprStmtContext PArrComp = text "array comprehension"
2514 pprStmtContext (PatGuard ctxt) = text "pattern guard for" $$ pprMatchContext ctxt
2515
2516 -- Drop the inner contexts when reporting errors, else we get
2517 -- Unexpected transform statement
2518 -- in a transformed branch of
2519 -- transformed branch of
2520 -- transformed branch of monad comprehension
2521 pprStmtContext (ParStmtCtxt c) =
2522 sdocWithPprDebug $ \dbg -> if dbg
2523 then sep [text "parallel branch of", pprAStmtContext c]
2524 else pprStmtContext c
2525 pprStmtContext (TransStmtCtxt c) =
2526 sdocWithPprDebug $ \dbg -> if dbg
2527 then sep [text "transformed branch of", pprAStmtContext c]
2528 else pprStmtContext c
2529
2530 instance (Outputable p, Outputable (NameOrRdrName p))
2531 => Outputable (HsStmtContext p) where
2532 ppr = pprStmtContext
2533
2534 -- Used to generate the string for a *runtime* error message
2535 matchContextErrString :: Outputable id
2536 => HsMatchContext id -> SDoc
2537 matchContextErrString (FunRhs{mc_fun=L _ fun}) = text "function" <+> ppr fun
2538 matchContextErrString CaseAlt = text "case"
2539 matchContextErrString IfAlt = text "multi-way if"
2540 matchContextErrString PatBindRhs = text "pattern binding"
2541 matchContextErrString RecUpd = text "record update"
2542 matchContextErrString LambdaExpr = text "lambda"
2543 matchContextErrString ProcExpr = text "proc"
2544 matchContextErrString ThPatSplice = panic "matchContextErrString" -- Not used at runtime
2545 matchContextErrString ThPatQuote = panic "matchContextErrString" -- Not used at runtime
2546 matchContextErrString PatSyn = panic "matchContextErrString" -- Not used at runtime
2547 matchContextErrString (StmtCtxt (ParStmtCtxt c)) = matchContextErrString (StmtCtxt c)
2548 matchContextErrString (StmtCtxt (TransStmtCtxt c)) = matchContextErrString (StmtCtxt c)
2549 matchContextErrString (StmtCtxt (PatGuard _)) = text "pattern guard"
2550 matchContextErrString (StmtCtxt GhciStmtCtxt) = text "interactive GHCi command"
2551 matchContextErrString (StmtCtxt DoExpr) = text "'do' block"
2552 matchContextErrString (StmtCtxt ArrowExpr) = text "'do' block"
2553 matchContextErrString (StmtCtxt MDoExpr) = text "'mdo' block"
2554 matchContextErrString (StmtCtxt ListComp) = text "list comprehension"
2555 matchContextErrString (StmtCtxt MonadComp) = text "monad comprehension"
2556 matchContextErrString (StmtCtxt PArrComp) = text "array comprehension"
2557
2558 pprMatchInCtxt :: (SourceTextX idR, OutputableBndrId idR,
2559 -- TODO:AZ these constraints do not make sense
2560 Outputable (NameOrRdrName (NameOrRdrName (IdP idR))),
2561 Outputable body)
2562 => Match idR body -> SDoc
2563 pprMatchInCtxt match = hang (text "In" <+> pprMatchContext (m_ctxt match)
2564 <> colon)
2565 4 (pprMatch match)
2566
2567 pprStmtInCtxt :: (SourceTextX idL, SourceTextX idR,
2568 OutputableBndrId idL, OutputableBndrId idR,
2569 Outputable body)
2570 => HsStmtContext (IdP idL) -> StmtLR idL idR body -> SDoc
2571 pprStmtInCtxt ctxt (LastStmt e _ _)
2572 | isListCompExpr ctxt -- For [ e | .. ], do not mutter about "stmts"
2573 = hang (text "In the expression:") 2 (ppr e)
2574
2575 pprStmtInCtxt ctxt stmt
2576 = hang (text "In a stmt of" <+> pprAStmtContext ctxt <> colon)
2577 2 (ppr_stmt stmt)
2578 where
2579 -- For Group and Transform Stmts, don't print the nested stmts!
2580 ppr_stmt (TransStmt { trS_by = by, trS_using = using
2581 , trS_form = form }) = pprTransStmt by using form
2582 ppr_stmt stmt = pprStmt stmt