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