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