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