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