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