Improve treatment of sectioned holes
[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 HsUnboundVar h@TrueExprHole{}
887 -> pp_infixly (unboundVarOcc h)
888 _ -> pp_prefixly
889 where
890 pp_expr = pprDebugParendExpr expr
891
892 pp_prefixly = hang (hsep [text " \\ x_ ->", ppr op])
893 4 (hsep [pp_expr, text "x_ )"])
894 pp_infixly v = (sep [pp_expr, pprInfixOcc v])
895
896 ppr_expr (SectionR op expr)
897 = case unLoc op of
898 HsVar (L _ v) -> pp_infixly v
899 HsConLikeOut c -> pp_infixly (conLikeName c)
900 HsUnboundVar h@TrueExprHole{}
901 -> pp_infixly (unboundVarOcc h)
902 _ -> pp_prefixly
903 where
904 pp_expr = pprDebugParendExpr expr
905
906 pp_prefixly = hang (hsep [text "( \\ x_ ->", ppr op, text "x_"])
907 4 (pp_expr <> rparen)
908 pp_infixly v = sep [pprInfixOcc v, pp_expr]
909
910 ppr_expr (ExplicitTuple exprs boxity)
911 = tupleParens (boxityTupleSort boxity) (fcat (ppr_tup_args $ map unLoc exprs))
912 where
913 ppr_tup_args [] = []
914 ppr_tup_args (Present e : es) = (ppr_lexpr e <> punc es) : ppr_tup_args es
915 ppr_tup_args (Missing _ : es) = punc es : ppr_tup_args es
916
917 punc (Present {} : _) = comma <> space
918 punc (Missing {} : _) = comma
919 punc [] = empty
920
921 ppr_expr (ExplicitSum alt arity expr _)
922 = text "(#" <+> ppr_bars (alt - 1) <+> ppr expr <+> ppr_bars (arity - alt) <+> text "#)"
923 where
924 ppr_bars n = hsep (replicate n (char '|'))
925
926 ppr_expr (HsLam matches)
927 = pprMatches matches
928
929 ppr_expr (HsLamCase matches)
930 = sep [ sep [text "\\case"],
931 nest 2 (pprMatches matches) ]
932
933 ppr_expr (HsCase expr matches@(MG { mg_alts = L _ [_] }))
934 = sep [ sep [text "case", nest 4 (ppr expr), ptext (sLit "of {")],
935 nest 2 (pprMatches matches) <+> char '}']
936 ppr_expr (HsCase expr matches)
937 = sep [ sep [text "case", nest 4 (ppr expr), ptext (sLit "of")],
938 nest 2 (pprMatches matches) ]
939
940 ppr_expr (HsIf _ e1 e2 e3)
941 = sep [hsep [text "if", nest 2 (ppr e1), ptext (sLit "then")],
942 nest 4 (ppr e2),
943 text "else",
944 nest 4 (ppr e3)]
945
946 ppr_expr (HsMultiIf _ alts)
947 = hang (text "if") 3 (vcat (map ppr_alt alts))
948 where ppr_alt (L _ (GRHS guards expr)) =
949 hang vbar 2 (ppr_one one_alt)
950 where
951 ppr_one [] = panic "ppr_exp HsMultiIf"
952 ppr_one (h:t) = hang h 2 (sep t)
953 one_alt = [ interpp'SP guards
954 , text "->" <+> pprDeeper (ppr expr) ]
955
956 -- special case: let ... in let ...
957 ppr_expr (HsLet (L _ binds) expr@(L _ (HsLet _ _)))
958 = sep [hang (text "let") 2 (hsep [pprBinds binds, ptext (sLit "in")]),
959 ppr_lexpr expr]
960
961 ppr_expr (HsLet (L _ binds) expr)
962 = sep [hang (text "let") 2 (pprBinds binds),
963 hang (text "in") 2 (ppr expr)]
964
965 ppr_expr (HsDo do_or_list_comp (L _ stmts) _) = pprDo do_or_list_comp stmts
966
967 ppr_expr (ExplicitList _ _ exprs)
968 = brackets (pprDeeperList fsep (punctuate comma (map ppr_lexpr exprs)))
969
970 ppr_expr (ExplicitPArr _ exprs)
971 = paBrackets (pprDeeperList fsep (punctuate comma (map ppr_lexpr exprs)))
972
973 ppr_expr (RecordCon { rcon_con_name = con_id, rcon_flds = rbinds })
974 = hang (ppr con_id) 2 (ppr rbinds)
975
976 ppr_expr (RecordUpd { rupd_expr = L _ aexp, rupd_flds = rbinds })
977 = hang (ppr aexp) 2 (braces (fsep (punctuate comma (map ppr rbinds))))
978
979 ppr_expr (ExprWithTySig expr sig)
980 = hang (nest 2 (ppr_lexpr expr) <+> dcolon)
981 4 (ppr sig)
982 ppr_expr (ExprWithTySigOut expr sig)
983 = hang (nest 2 (ppr_lexpr expr) <+> dcolon)
984 4 (ppr sig)
985
986 ppr_expr (ArithSeq _ _ info) = brackets (ppr info)
987 ppr_expr (PArrSeq _ info) = paBrackets (ppr info)
988
989 ppr_expr EWildPat = char '_'
990 ppr_expr (ELazyPat e) = char '~' <> ppr e
991 ppr_expr (EAsPat v e) = ppr v <> char '@' <> ppr e
992 ppr_expr (EViewPat p e) = ppr p <+> text "->" <+> ppr e
993
994 ppr_expr (HsSCC st (StringLiteral stl lbl) expr)
995 = sep [ pprWithSourceText st (text "{-# SCC")
996 -- no doublequotes if stl empty, for the case where the SCC was written
997 -- without quotes.
998 <+> pprWithSourceText stl (ftext lbl) <+> text "#-}",
999 ppr expr ]
1000
1001 ppr_expr (HsWrap co_fn e)
1002 = pprHsWrapper co_fn (\parens -> if parens then pprExpr e
1003 else pprExpr e)
1004
1005 ppr_expr (HsSpliceE s) = pprSplice s
1006 ppr_expr (HsBracket b) = pprHsBracket b
1007 ppr_expr (HsRnBracketOut e []) = ppr e
1008 ppr_expr (HsRnBracketOut e ps) = ppr e $$ text "pending(rn)" <+> ppr ps
1009 ppr_expr (HsTcBracketOut e []) = ppr e
1010 ppr_expr (HsTcBracketOut e ps) = ppr e $$ text "pending(tc)" <+> ppr ps
1011
1012 ppr_expr (HsProc pat (L _ (HsCmdTop cmd _ _ _)))
1013 = hsep [text "proc", ppr pat, ptext (sLit "->"), ppr cmd]
1014
1015 ppr_expr (HsStatic _ e)
1016 = hsep [text "static", ppr e]
1017
1018 ppr_expr (HsTick tickish exp)
1019 = pprTicks (ppr exp) $
1020 ppr tickish <+> ppr_lexpr exp
1021 ppr_expr (HsBinTick tickIdTrue tickIdFalse exp)
1022 = pprTicks (ppr exp) $
1023 hcat [text "bintick<",
1024 ppr tickIdTrue,
1025 text ",",
1026 ppr tickIdFalse,
1027 text ">(",
1028 ppr exp, text ")"]
1029 ppr_expr (HsTickPragma _ externalSrcLoc _ exp)
1030 = pprTicks (ppr exp) $
1031 hcat [text "tickpragma<",
1032 pprExternalSrcLoc externalSrcLoc,
1033 text ">(",
1034 ppr exp,
1035 text ")"]
1036
1037 ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp True)
1038 = hsep [ppr_lexpr arrow, larrowt, ppr_lexpr arg]
1039 ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp False)
1040 = hsep [ppr_lexpr arg, arrowt, ppr_lexpr arrow]
1041 ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp True)
1042 = hsep [ppr_lexpr arrow, larrowtt, ppr_lexpr arg]
1043 ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp False)
1044 = hsep [ppr_lexpr arg, arrowtt, ppr_lexpr arrow]
1045
1046 ppr_expr (HsArrForm (L _ (HsVar (L _ v))) (Just _) [arg1, arg2])
1047 = sep [pprCmdArg (unLoc arg1), hsep [pprInfixOcc v, pprCmdArg (unLoc arg2)]]
1048 ppr_expr (HsArrForm (L _ (HsConLikeOut c)) (Just _) [arg1, arg2])
1049 = sep [pprCmdArg (unLoc arg1), hsep [pprInfixOcc (conLikeName c), pprCmdArg (unLoc arg2)]]
1050 ppr_expr (HsArrForm op _ args)
1051 = hang (text "(|" <+> ppr_lexpr op)
1052 4 (sep (map (pprCmdArg.unLoc) args) <+> text "|)")
1053 ppr_expr (HsRecFld f) = ppr f
1054
1055 -- We must tiresomely make the "id" parameter to the LHsWcType existential
1056 -- because it's different in the HsAppType case and the HsAppTypeOut case
1057 -- | Located Haskell Wildcard Type Expression
1058 data LHsWcTypeX = forall p. (SourceTextX p, OutputableBndrId p)
1059 => LHsWcTypeX (LHsWcType p)
1060
1061 ppr_apps :: (SourceTextX p, OutputableBndrId p) => HsExpr p
1062 -> [Either (LHsExpr p) LHsWcTypeX]
1063 -> SDoc
1064 ppr_apps (HsApp (L _ fun) arg) args
1065 = ppr_apps fun (Left arg : args)
1066 ppr_apps (HsAppType (L _ fun) arg) args
1067 = ppr_apps fun (Right (LHsWcTypeX arg) : args)
1068 ppr_apps (HsAppTypeOut (L _ fun) arg) args
1069 = ppr_apps fun (Right (LHsWcTypeX arg) : args)
1070 ppr_apps fun args = hang (ppr_expr fun) 2 (sep (map pp args))
1071 where
1072 pp (Left arg) = ppr arg
1073 pp (Right (LHsWcTypeX (HsWC { hswc_body = L _ arg })))
1074 = char '@' <> pprHsType arg
1075
1076 pprExternalSrcLoc :: (StringLiteral,(Int,Int),(Int,Int)) -> SDoc
1077 pprExternalSrcLoc (StringLiteral _ src,(n1,n2),(n3,n4))
1078 = ppr (src,(n1,n2),(n3,n4))
1079
1080 {-
1081 HsSyn records exactly where the user put parens, with HsPar.
1082 So generally speaking we print without adding any parens.
1083 However, some code is internally generated, and in some places
1084 parens are absolutely required; so for these places we use
1085 pprParendLExpr (but don't print double parens of course).
1086
1087 For operator applications we don't add parens, because the operator
1088 fixities should do the job, except in debug mode (-dppr-debug) so we
1089 can see the structure of the parse tree.
1090 -}
1091
1092 pprDebugParendExpr :: (SourceTextX p, OutputableBndrId p) => LHsExpr p -> SDoc
1093 pprDebugParendExpr expr
1094 = getPprStyle (\sty ->
1095 if debugStyle sty then pprParendLExpr expr
1096 else pprLExpr expr)
1097
1098 pprParendLExpr :: (SourceTextX p, OutputableBndrId p) => LHsExpr p -> SDoc
1099 pprParendLExpr (L _ e) = pprParendExpr e
1100
1101 pprParendExpr :: (SourceTextX p, OutputableBndrId p) => HsExpr p -> SDoc
1102 pprParendExpr expr
1103 | hsExprNeedsParens expr = parens (pprExpr expr)
1104 | otherwise = pprExpr expr
1105 -- Using pprLExpr makes sure that we go 'deeper'
1106 -- I think that is usually (always?) right
1107
1108 hsExprNeedsParens :: HsExpr id -> Bool
1109 -- True of expressions for which '(e)' and 'e'
1110 -- mean the same thing
1111 hsExprNeedsParens (ArithSeq {}) = False
1112 hsExprNeedsParens (PArrSeq {}) = False
1113 hsExprNeedsParens (HsLit {}) = False
1114 hsExprNeedsParens (HsOverLit {}) = False
1115 hsExprNeedsParens (HsVar {}) = False
1116 hsExprNeedsParens (HsUnboundVar {}) = False
1117 hsExprNeedsParens (HsConLikeOut {}) = False
1118 hsExprNeedsParens (HsIPVar {}) = False
1119 hsExprNeedsParens (HsOverLabel {}) = False
1120 hsExprNeedsParens (ExplicitTuple {}) = False
1121 hsExprNeedsParens (ExplicitList {}) = False
1122 hsExprNeedsParens (ExplicitPArr {}) = False
1123 hsExprNeedsParens (HsPar {}) = False
1124 hsExprNeedsParens (HsBracket {}) = False
1125 hsExprNeedsParens (HsRnBracketOut {}) = False
1126 hsExprNeedsParens (HsTcBracketOut {}) = False
1127 hsExprNeedsParens (HsDo sc _ _)
1128 | isListCompExpr sc = False
1129 hsExprNeedsParens (HsRecFld{}) = False
1130 hsExprNeedsParens (RecordCon{}) = False
1131 hsExprNeedsParens (HsSpliceE{}) = False
1132 hsExprNeedsParens (RecordUpd{}) = False
1133 hsExprNeedsParens (HsWrap _ e) = hsExprNeedsParens e
1134 hsExprNeedsParens _ = True
1135
1136
1137 isAtomicHsExpr :: HsExpr id -> Bool
1138 -- True of a single token
1139 isAtomicHsExpr (HsVar {}) = True
1140 isAtomicHsExpr (HsConLikeOut {}) = True
1141 isAtomicHsExpr (HsLit {}) = True
1142 isAtomicHsExpr (HsOverLit {}) = True
1143 isAtomicHsExpr (HsIPVar {}) = True
1144 isAtomicHsExpr (HsOverLabel {}) = True
1145 isAtomicHsExpr (HsUnboundVar {}) = True
1146 isAtomicHsExpr (HsWrap _ e) = isAtomicHsExpr e
1147 isAtomicHsExpr (HsPar e) = isAtomicHsExpr (unLoc e)
1148 isAtomicHsExpr (HsRecFld{}) = True
1149 isAtomicHsExpr _ = False
1150
1151 {-
1152 ************************************************************************
1153 * *
1154 \subsection{Commands (in arrow abstractions)}
1155 * *
1156 ************************************************************************
1157
1158 We re-use HsExpr to represent these.
1159 -}
1160
1161 -- | Located Haskell Command (for arrow syntax)
1162 type LHsCmd id = Located (HsCmd id)
1163
1164 -- | Haskell Command (e.g. a "statement" in an Arrow proc block)
1165 data HsCmd id
1166 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.Annlarrowtail',
1167 -- 'ApiAnnotation.Annrarrowtail','ApiAnnotation.AnnLarrowtail',
1168 -- 'ApiAnnotation.AnnRarrowtail'
1169
1170 -- For details on above see note [Api annotations] in ApiAnnotation
1171 = HsCmdArrApp -- Arrow tail, or arrow application (f -< arg)
1172 (LHsExpr id) -- arrow expression, f
1173 (LHsExpr id) -- input expression, arg
1174 (PostTc id Type) -- type of the arrow expressions f,
1175 -- of the form a t t', where arg :: t
1176 HsArrAppType -- higher-order (-<<) or first-order (-<)
1177 Bool -- True => right-to-left (f -< arg)
1178 -- False => left-to-right (arg >- f)
1179
1180 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpenB' @'(|'@,
1181 -- 'ApiAnnotation.AnnCloseB' @'|)'@
1182
1183 -- For details on above see note [Api annotations] in ApiAnnotation
1184 | HsCmdArrForm -- Command formation, (| e cmd1 .. cmdn |)
1185 (LHsExpr id) -- The operator.
1186 -- After type-checking, a type abstraction to be
1187 -- applied to the type of the local environment tuple
1188 LexicalFixity -- Whether the operator appeared prefix or infix when
1189 -- parsed.
1190 (Maybe Fixity) -- fixity (filled in by the renamer), for forms that
1191 -- were converted from OpApp's by the renamer
1192 [LHsCmdTop id] -- argument commands
1193
1194 | HsCmdApp (LHsCmd id)
1195 (LHsExpr id)
1196
1197 | HsCmdLam (MatchGroup id (LHsCmd id)) -- kappa
1198 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLam',
1199 -- 'ApiAnnotation.AnnRarrow',
1200
1201 -- For details on above see note [Api annotations] in ApiAnnotation
1202
1203 | HsCmdPar (LHsCmd id) -- parenthesised command
1204 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@,
1205 -- 'ApiAnnotation.AnnClose' @')'@
1206
1207 -- For details on above see note [Api annotations] in ApiAnnotation
1208
1209 | HsCmdCase (LHsExpr id)
1210 (MatchGroup id (LHsCmd id)) -- bodies are HsCmd's
1211 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnCase',
1212 -- 'ApiAnnotation.AnnOf','ApiAnnotation.AnnOpen' @'{'@,
1213 -- 'ApiAnnotation.AnnClose' @'}'@
1214
1215 -- For details on above see note [Api annotations] in ApiAnnotation
1216
1217 | HsCmdIf (Maybe (SyntaxExpr id)) -- cond function
1218 (LHsExpr id) -- predicate
1219 (LHsCmd id) -- then part
1220 (LHsCmd id) -- else part
1221 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnIf',
1222 -- 'ApiAnnotation.AnnSemi',
1223 -- 'ApiAnnotation.AnnThen','ApiAnnotation.AnnSemi',
1224 -- 'ApiAnnotation.AnnElse',
1225
1226 -- For details on above see note [Api annotations] in ApiAnnotation
1227
1228 | HsCmdLet (LHsLocalBinds id) -- let(rec)
1229 (LHsCmd id)
1230 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLet',
1231 -- 'ApiAnnotation.AnnOpen' @'{'@,
1232 -- 'ApiAnnotation.AnnClose' @'}'@,'ApiAnnotation.AnnIn'
1233
1234 -- For details on above see note [Api annotations] in ApiAnnotation
1235
1236 | HsCmdDo (Located [CmdLStmt id])
1237 (PostTc id Type) -- Type of the whole expression
1238 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDo',
1239 -- 'ApiAnnotation.AnnOpen', 'ApiAnnotation.AnnSemi',
1240 -- 'ApiAnnotation.AnnVbar',
1241 -- 'ApiAnnotation.AnnClose'
1242
1243 -- For details on above see note [Api annotations] in ApiAnnotation
1244
1245 | HsCmdWrap HsWrapper
1246 (HsCmd id) -- If cmd :: arg1 --> res
1247 -- wrap :: arg1 "->" arg2
1248 -- Then (HsCmdWrap wrap cmd) :: arg2 --> res
1249 deriving instance (DataId id) => Data (HsCmd id)
1250
1251 -- | Haskell Array Application Type
1252 data HsArrAppType = HsHigherOrderApp | HsFirstOrderApp
1253 deriving Data
1254
1255
1256 {- | Top-level command, introducing a new arrow.
1257 This may occur inside a proc (where the stack is empty) or as an
1258 argument of a command-forming operator.
1259 -}
1260
1261 -- | Located Haskell Top-level Command
1262 type LHsCmdTop p = Located (HsCmdTop p)
1263
1264 -- | Haskell Top-level Command
1265 data HsCmdTop p
1266 = HsCmdTop (LHsCmd p)
1267 (PostTc p Type) -- Nested tuple of inputs on the command's stack
1268 (PostTc p Type) -- return type of the command
1269 (CmdSyntaxTable p) -- See Note [CmdSyntaxTable]
1270 deriving instance (DataId p) => Data (HsCmdTop p)
1271
1272 instance (SourceTextX p, OutputableBndrId p) => Outputable (HsCmd p) where
1273 ppr cmd = pprCmd cmd
1274
1275 -----------------------
1276 -- pprCmd and pprLCmd call pprDeeper;
1277 -- the underscore versions do not
1278 pprLCmd :: (SourceTextX p, OutputableBndrId p) => LHsCmd p -> SDoc
1279 pprLCmd (L _ c) = pprCmd c
1280
1281 pprCmd :: (SourceTextX p, OutputableBndrId p) => HsCmd p -> SDoc
1282 pprCmd c | isQuietHsCmd c = ppr_cmd c
1283 | otherwise = pprDeeper (ppr_cmd c)
1284
1285 isQuietHsCmd :: HsCmd id -> Bool
1286 -- Parentheses do display something, but it gives little info and
1287 -- if we go deeper when we go inside them then we get ugly things
1288 -- like (...)
1289 isQuietHsCmd (HsCmdPar _) = True
1290 -- applications don't display anything themselves
1291 isQuietHsCmd (HsCmdApp _ _) = True
1292 isQuietHsCmd _ = False
1293
1294 -----------------------
1295 ppr_lcmd :: (SourceTextX p, OutputableBndrId p) => LHsCmd p -> SDoc
1296 ppr_lcmd c = ppr_cmd (unLoc c)
1297
1298 ppr_cmd :: forall p. (SourceTextX p, OutputableBndrId p) => HsCmd p -> SDoc
1299 ppr_cmd (HsCmdPar c) = parens (ppr_lcmd c)
1300
1301 ppr_cmd (HsCmdApp c e)
1302 = let (fun, args) = collect_args c [e] in
1303 hang (ppr_lcmd fun) 2 (sep (map ppr args))
1304 where
1305 collect_args (L _ (HsCmdApp fun arg)) args = collect_args fun (arg:args)
1306 collect_args fun args = (fun, args)
1307
1308 ppr_cmd (HsCmdLam matches)
1309 = pprMatches matches
1310
1311 ppr_cmd (HsCmdCase expr matches)
1312 = sep [ sep [text "case", nest 4 (ppr expr), ptext (sLit "of")],
1313 nest 2 (pprMatches matches) ]
1314
1315 ppr_cmd (HsCmdIf _ e ct ce)
1316 = sep [hsep [text "if", nest 2 (ppr e), ptext (sLit "then")],
1317 nest 4 (ppr ct),
1318 text "else",
1319 nest 4 (ppr ce)]
1320
1321 -- special case: let ... in let ...
1322 ppr_cmd (HsCmdLet (L _ binds) cmd@(L _ (HsCmdLet _ _)))
1323 = sep [hang (text "let") 2 (hsep [pprBinds binds, ptext (sLit "in")]),
1324 ppr_lcmd cmd]
1325
1326 ppr_cmd (HsCmdLet (L _ binds) cmd)
1327 = sep [hang (text "let") 2 (pprBinds binds),
1328 hang (text "in") 2 (ppr cmd)]
1329
1330 ppr_cmd (HsCmdDo (L _ stmts) _) = pprDo ArrowExpr stmts
1331
1332 ppr_cmd (HsCmdWrap w cmd)
1333 = pprHsWrapper w (\_ -> parens (ppr_cmd cmd))
1334 ppr_cmd (HsCmdArrApp arrow arg _ HsFirstOrderApp True)
1335 = hsep [ppr_lexpr arrow, larrowt, ppr_lexpr arg]
1336 ppr_cmd (HsCmdArrApp arrow arg _ HsFirstOrderApp False)
1337 = hsep [ppr_lexpr arg, arrowt, ppr_lexpr arrow]
1338 ppr_cmd (HsCmdArrApp arrow arg _ HsHigherOrderApp True)
1339 = hsep [ppr_lexpr arrow, larrowtt, ppr_lexpr arg]
1340 ppr_cmd (HsCmdArrApp arrow arg _ HsHigherOrderApp False)
1341 = hsep [ppr_lexpr arg, arrowtt, ppr_lexpr arrow]
1342
1343 ppr_cmd (HsCmdArrForm (L _ (HsVar (L _ v))) _ (Just _) [arg1, arg2])
1344 = hang (pprCmdArg (unLoc arg1)) 4 (sep [ pprInfixOcc v
1345 , pprCmdArg (unLoc arg2)])
1346 ppr_cmd (HsCmdArrForm (L _ (HsVar (L _ v))) Infix _ [arg1, arg2])
1347 = hang (pprCmdArg (unLoc arg1)) 4 (sep [ pprInfixOcc v
1348 , pprCmdArg (unLoc arg2)])
1349 ppr_cmd (HsCmdArrForm (L _ (HsConLikeOut c)) _ (Just _) [arg1, arg2])
1350 = hang (pprCmdArg (unLoc arg1)) 4 (sep [ pprInfixOcc (conLikeName c)
1351 , pprCmdArg (unLoc arg2)])
1352 ppr_cmd (HsCmdArrForm (L _ (HsConLikeOut c)) Infix _ [arg1, arg2])
1353 = hang (pprCmdArg (unLoc arg1)) 4 (sep [ pprInfixOcc (conLikeName c)
1354 , pprCmdArg (unLoc arg2)])
1355 ppr_cmd (HsCmdArrForm op _ _ args)
1356 = hang (text "(|" <> ppr_lexpr op)
1357 4 (sep (map (pprCmdArg.unLoc) args) <> text "|)")
1358
1359 pprCmdArg :: (SourceTextX p, OutputableBndrId p) => HsCmdTop p -> SDoc
1360 pprCmdArg (HsCmdTop cmd _ _ _)
1361 = ppr_lcmd cmd
1362
1363 instance (SourceTextX p, OutputableBndrId p) => Outputable (HsCmdTop p) where
1364 ppr = pprCmdArg
1365
1366 {-
1367 ************************************************************************
1368 * *
1369 \subsection{Record binds}
1370 * *
1371 ************************************************************************
1372 -}
1373
1374 -- | Haskell Record Bindings
1375 type HsRecordBinds p = HsRecFields p (LHsExpr p)
1376
1377 {-
1378 ************************************************************************
1379 * *
1380 \subsection{@Match@, @GRHSs@, and @GRHS@ datatypes}
1381 * *
1382 ************************************************************************
1383
1384 @Match@es are sets of pattern bindings and right hand sides for
1385 functions, patterns or case branches. For example, if a function @g@
1386 is defined as:
1387 \begin{verbatim}
1388 g (x,y) = y
1389 g ((x:ys),y) = y+1,
1390 \end{verbatim}
1391 then \tr{g} has two @Match@es: @(x,y) = y@ and @((x:ys),y) = y+1@.
1392
1393 It is always the case that each element of an @[Match]@ list has the
1394 same number of @pats@s inside it. This corresponds to saying that
1395 a function defined by pattern matching must have the same number of
1396 patterns in each equation.
1397 -}
1398
1399 data MatchGroup p body
1400 = MG { mg_alts :: Located [LMatch p body] -- The alternatives
1401 , mg_arg_tys :: [PostTc p Type] -- Types of the arguments, t1..tn
1402 , mg_res_ty :: PostTc p Type -- Type of the result, tr
1403 , mg_origin :: Origin }
1404 -- The type is the type of the entire group
1405 -- t1 -> ... -> tn -> tr
1406 -- where there are n patterns
1407 deriving instance (Data body,DataId p) => Data (MatchGroup p body)
1408
1409 -- | Located Match
1410 type LMatch id body = Located (Match id body)
1411 -- ^ May have 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnSemi' when in a
1412 -- list
1413
1414 -- For details on above see note [Api annotations] in ApiAnnotation
1415 data Match p body
1416 = Match {
1417 m_ctxt :: HsMatchContext (NameOrRdrName (IdP p)),
1418 -- See note [m_ctxt in Match]
1419 m_pats :: [LPat p], -- The patterns
1420 m_grhss :: (GRHSs p body)
1421 }
1422 deriving instance (Data body,DataId p) => Data (Match p body)
1423
1424 instance (SourceTextX idR, OutputableBndrId idR, Outputable body)
1425 => Outputable (Match idR body) where
1426 ppr = pprMatch
1427
1428 {-
1429 Note [m_ctxt in Match]
1430 ~~~~~~~~~~~~~~~~~~~~~~
1431
1432 A Match can occur in a number of contexts, such as a FunBind, HsCase, HsLam and
1433 so on.
1434
1435 In order to simplify tooling processing and pretty print output, the provenance
1436 is captured in an HsMatchContext.
1437
1438 This is particularly important for the API Annotations for a multi-equation
1439 FunBind.
1440
1441 The parser initially creates a FunBind with a single Match in it for
1442 every function definition it sees.
1443
1444 These are then grouped together by getMonoBind into a single FunBind,
1445 where all the Matches are combined.
1446
1447 In the process, all the original FunBind fun_id's bar one are
1448 discarded, including the locations.
1449
1450 This causes a problem for source to source conversions via API
1451 Annotations, so the original fun_ids and infix flags are preserved in
1452 the Match, when it originates from a FunBind.
1453
1454 Example infix function definition requiring individual API Annotations
1455
1456 (&&& ) [] [] = []
1457 xs &&& [] = xs
1458 ( &&& ) [] ys = ys
1459
1460
1461
1462 -}
1463
1464
1465 isInfixMatch :: Match id body -> Bool
1466 isInfixMatch match = case m_ctxt match of
1467 FunRhs {mc_fixity = Infix} -> True
1468 _ -> False
1469
1470 isEmptyMatchGroup :: MatchGroup id body -> Bool
1471 isEmptyMatchGroup (MG { mg_alts = ms }) = null $ unLoc ms
1472
1473 -- | Is there only one RHS in this list of matches?
1474 isSingletonMatchGroup :: [LMatch id body] -> Bool
1475 isSingletonMatchGroup matches
1476 | [L _ match] <- matches
1477 , Match { m_grhss = GRHSs { grhssGRHSs = [_] } } <- match
1478 = True
1479 | otherwise
1480 = False
1481
1482 matchGroupArity :: MatchGroup id body -> Arity
1483 -- Precondition: MatchGroup is non-empty
1484 -- This is called before type checking, when mg_arg_tys is not set
1485 matchGroupArity (MG { mg_alts = alts })
1486 | L _ (alt1:_) <- alts = length (hsLMatchPats alt1)
1487 | otherwise = panic "matchGroupArity"
1488
1489 hsLMatchPats :: LMatch id body -> [LPat id]
1490 hsLMatchPats (L _ (Match { m_pats = pats })) = pats
1491
1492 -- | Guarded Right-Hand Sides
1493 --
1494 -- GRHSs are used both for pattern bindings and for Matches
1495 --
1496 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnVbar',
1497 -- 'ApiAnnotation.AnnEqual','ApiAnnotation.AnnWhere',
1498 -- 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose'
1499 -- 'ApiAnnotation.AnnRarrow','ApiAnnotation.AnnSemi'
1500
1501 -- For details on above see note [Api annotations] in ApiAnnotation
1502 data GRHSs p body
1503 = GRHSs {
1504 grhssGRHSs :: [LGRHS p body], -- ^ Guarded RHSs
1505 grhssLocalBinds :: LHsLocalBinds p -- ^ The where clause
1506 }
1507 deriving instance (Data body,DataId p) => Data (GRHSs p body)
1508
1509 -- | Located Guarded Right-Hand Side
1510 type LGRHS id body = Located (GRHS id body)
1511
1512 -- | Guarded Right Hand Side.
1513 data GRHS id body = GRHS [GuardLStmt id] -- Guards
1514 body -- Right hand side
1515 deriving instance (Data body,DataId id) => Data (GRHS id body)
1516
1517 -- We know the list must have at least one @Match@ in it.
1518
1519 pprMatches :: (SourceTextX idR, OutputableBndrId idR, Outputable body)
1520 => MatchGroup idR body -> SDoc
1521 pprMatches MG { mg_alts = matches }
1522 = vcat (map pprMatch (map unLoc (unLoc matches)))
1523 -- Don't print the type; it's only a place-holder before typechecking
1524
1525 -- Exported to HsBinds, which can't see the defn of HsMatchContext
1526 pprFunBind :: (SourceTextX idR, OutputableBndrId idR, Outputable body)
1527 => MatchGroup idR body -> SDoc
1528 pprFunBind matches = pprMatches matches
1529
1530 -- Exported to HsBinds, which can't see the defn of HsMatchContext
1531 pprPatBind :: forall bndr p body. (SourceTextX p, SourceTextX bndr,
1532 OutputableBndrId bndr,
1533 OutputableBndrId p,
1534 Outputable body)
1535 => LPat bndr -> GRHSs p body -> SDoc
1536 pprPatBind pat (grhss)
1537 = sep [ppr pat, nest 2 (pprGRHSs (PatBindRhs :: HsMatchContext (IdP p)) grhss)]
1538
1539 pprMatch :: (SourceTextX idR, OutputableBndrId idR, Outputable body)
1540 => Match idR body -> SDoc
1541 pprMatch match
1542 = sep [ sep (herald : map (nest 2 . pprParendLPat) other_pats)
1543 , nest 2 (pprGRHSs ctxt (m_grhss match)) ]
1544 where
1545 ctxt = m_ctxt match
1546 (herald, other_pats)
1547 = case ctxt of
1548 FunRhs {mc_fun=L _ fun, mc_fixity=fixity, mc_strictness=strictness}
1549 | strictness == SrcStrict -> ASSERT(null $ m_pats match)
1550 (char '!'<>pprPrefixOcc fun, m_pats match)
1551 -- a strict variable binding
1552 | fixity == Prefix -> (pprPrefixOcc fun, m_pats match)
1553 -- f x y z = e
1554 -- Not pprBndr; the AbsBinds will
1555 -- have printed the signature
1556
1557 | null pats2 -> (pp_infix, [])
1558 -- x &&& y = e
1559
1560 | otherwise -> (parens pp_infix, pats2)
1561 -- (x &&& y) z = e
1562 where
1563 pp_infix = pprParendLPat pat1 <+> pprInfixOcc fun <+> pprParendLPat pat2
1564
1565 LambdaExpr -> (char '\\', m_pats match)
1566
1567 _ -> ASSERT2( null pats1, ppr ctxt $$ ppr pat1 $$ ppr pats1 )
1568 (ppr pat1, []) -- No parens around the single pat
1569
1570 (pat1:pats1) = m_pats match
1571 (pat2:pats2) = pats1
1572
1573 pprGRHSs :: (SourceTextX idR, OutputableBndrId idR, Outputable body)
1574 => HsMatchContext idL -> GRHSs idR body -> SDoc
1575 pprGRHSs ctxt (GRHSs grhss (L _ binds))
1576 = vcat (map (pprGRHS ctxt . unLoc) grhss)
1577 -- Print the "where" even if the contents of the binds is empty. Only
1578 -- EmptyLocalBinds means no "where" keyword
1579 $$ ppUnless (eqEmptyLocalBinds binds)
1580 (text "where" $$ nest 4 (pprBinds binds))
1581
1582 pprGRHS :: (SourceTextX idR, OutputableBndrId idR, Outputable body)
1583 => HsMatchContext idL -> GRHS idR body -> SDoc
1584 pprGRHS ctxt (GRHS [] body)
1585 = pp_rhs ctxt body
1586
1587 pprGRHS ctxt (GRHS guards body)
1588 = sep [vbar <+> interpp'SP guards, pp_rhs ctxt body]
1589
1590 pp_rhs :: Outputable body => HsMatchContext idL -> body -> SDoc
1591 pp_rhs ctxt rhs = matchSeparator ctxt <+> pprDeeper (ppr rhs)
1592
1593 {-
1594 ************************************************************************
1595 * *
1596 \subsection{Do stmts and list comprehensions}
1597 * *
1598 ************************************************************************
1599 -}
1600
1601 -- | Located @do@ block Statement
1602 type LStmt id body = Located (StmtLR id id body)
1603
1604 -- | Located Statement with separate Left and Right id's
1605 type LStmtLR idL idR body = Located (StmtLR idL idR body)
1606
1607 -- | @do@ block Statement
1608 type Stmt id body = StmtLR id id body
1609
1610 -- | Command Located Statement
1611 type CmdLStmt id = LStmt id (LHsCmd id)
1612
1613 -- | Command Statement
1614 type CmdStmt id = Stmt id (LHsCmd id)
1615
1616 -- | Expression Located Statement
1617 type ExprLStmt id = LStmt id (LHsExpr id)
1618
1619 -- | Expression Statement
1620 type ExprStmt id = Stmt id (LHsExpr id)
1621
1622 -- | Guard Located Statement
1623 type GuardLStmt id = LStmt id (LHsExpr id)
1624
1625 -- | Guard Statement
1626 type GuardStmt id = Stmt id (LHsExpr id)
1627
1628 -- | Ghci Located Statement
1629 type GhciLStmt id = LStmt id (LHsExpr id)
1630
1631 -- | Ghci Statement
1632 type GhciStmt id = Stmt id (LHsExpr id)
1633
1634 -- The SyntaxExprs in here are used *only* for do-notation and monad
1635 -- comprehensions, which have rebindable syntax. Otherwise they are unused.
1636 -- | API Annotations when in qualifier lists or guards
1637 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnVbar',
1638 -- 'ApiAnnotation.AnnComma','ApiAnnotation.AnnThen',
1639 -- 'ApiAnnotation.AnnBy','ApiAnnotation.AnnBy',
1640 -- 'ApiAnnotation.AnnGroup','ApiAnnotation.AnnUsing'
1641
1642 -- For details on above see note [Api annotations] in ApiAnnotation
1643 data StmtLR idL idR body -- body should always be (LHs**** idR)
1644 = LastStmt -- Always the last Stmt in ListComp, MonadComp, PArrComp,
1645 -- and (after the renamer) DoExpr, MDoExpr
1646 -- Not used for GhciStmtCtxt, PatGuard, which scope over other stuff
1647 body
1648 Bool -- True <=> return was stripped by ApplicativeDo
1649 (SyntaxExpr idR) -- The return operator, used only for
1650 -- MonadComp For ListComp, PArrComp, we
1651 -- use the baked-in 'return' For DoExpr,
1652 -- MDoExpr, we don't apply a 'return' at
1653 -- all See Note [Monad Comprehensions] |
1654 -- - 'ApiAnnotation.AnnKeywordId' :
1655 -- 'ApiAnnotation.AnnLarrow'
1656
1657 -- For details on above see note [Api annotations] in ApiAnnotation
1658 | BindStmt (LPat idL)
1659 body
1660 (SyntaxExpr idR) -- The (>>=) operator; see Note [The type of bind in Stmts]
1661 (SyntaxExpr idR) -- The fail operator
1662 -- The fail operator is noSyntaxExpr
1663 -- if the pattern match can't fail
1664
1665 (PostTc idR Type) -- result type of the function passed to bind;
1666 -- that is, S in (>>=) :: Q -> (R -> S) -> T
1667
1668 -- | 'ApplicativeStmt' represents an applicative expression built with
1669 -- <$> and <*>. It is generated by the renamer, and is desugared into the
1670 -- appropriate applicative expression by the desugarer, but it is intended
1671 -- to be invisible in error messages.
1672 --
1673 -- For full details, see Note [ApplicativeDo] in RnExpr
1674 --
1675 | ApplicativeStmt
1676 [ ( SyntaxExpr idR
1677 , ApplicativeArg idL idR) ]
1678 -- [(<$>, e1), (<*>, e2), ..., (<*>, en)]
1679 (Maybe (SyntaxExpr idR)) -- 'join', if necessary
1680 (PostTc idR Type) -- Type of the body
1681
1682 | BodyStmt body -- See Note [BodyStmt]
1683 (SyntaxExpr idR) -- The (>>) operator
1684 (SyntaxExpr idR) -- The `guard` operator; used only in MonadComp
1685 -- See notes [Monad Comprehensions]
1686 (PostTc idR Type) -- Element type of the RHS (used for arrows)
1687
1688 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLet'
1689 -- 'ApiAnnotation.AnnOpen' @'{'@,'ApiAnnotation.AnnClose' @'}'@,
1690
1691 -- For details on above see note [Api annotations] in ApiAnnotation
1692 | LetStmt (LHsLocalBindsLR idL idR)
1693
1694 -- ParStmts only occur in a list/monad comprehension
1695 | ParStmt [ParStmtBlock idL idR]
1696 (HsExpr idR) -- Polymorphic `mzip` for monad comprehensions
1697 (SyntaxExpr idR) -- The `>>=` operator
1698 -- See notes [Monad Comprehensions]
1699 (PostTc idR Type) -- S in (>>=) :: Q -> (R -> S) -> T
1700 -- After renaming, the ids are the binders
1701 -- bound by the stmts and used after themp
1702
1703 | TransStmt {
1704 trS_form :: TransForm,
1705 trS_stmts :: [ExprLStmt idL], -- Stmts to the *left* of the 'group'
1706 -- which generates the tuples to be grouped
1707
1708 trS_bndrs :: [(IdP idR, IdP idR)], -- See Note [TransStmt binder map]
1709
1710 trS_using :: LHsExpr idR,
1711 trS_by :: Maybe (LHsExpr idR), -- "by e" (optional)
1712 -- Invariant: if trS_form = GroupBy, then grp_by = Just e
1713
1714 trS_ret :: SyntaxExpr idR, -- The monomorphic 'return' function for
1715 -- the inner monad comprehensions
1716 trS_bind :: SyntaxExpr idR, -- The '(>>=)' operator
1717 trS_bind_arg_ty :: PostTc idR Type, -- R in (>>=) :: Q -> (R -> S) -> T
1718 trS_fmap :: HsExpr idR -- The polymorphic 'fmap' function for desugaring
1719 -- Only for 'group' forms
1720 -- Just a simple HsExpr, because it's
1721 -- too polymorphic for tcSyntaxOp
1722 } -- See Note [Monad Comprehensions]
1723
1724 -- Recursive statement (see Note [How RecStmt works] below)
1725 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnRec'
1726
1727 -- For details on above see note [Api annotations] in ApiAnnotation
1728 | RecStmt
1729 { recS_stmts :: [LStmtLR idL idR body]
1730
1731 -- The next two fields are only valid after renaming
1732 , recS_later_ids :: [IdP idR]
1733 -- The ids are a subset of the variables bound by the
1734 -- stmts that are used in stmts that follow the RecStmt
1735
1736 , recS_rec_ids :: [IdP idR]
1737 -- Ditto, but these variables are the "recursive" ones,
1738 -- that are used before they are bound in the stmts of
1739 -- the RecStmt.
1740 -- An Id can be in both groups
1741 -- Both sets of Ids are (now) treated monomorphically
1742 -- See Note [How RecStmt works] for why they are separate
1743
1744 -- Rebindable syntax
1745 , recS_bind_fn :: SyntaxExpr idR -- The bind function
1746 , recS_ret_fn :: SyntaxExpr idR -- The return function
1747 , recS_mfix_fn :: SyntaxExpr idR -- The mfix function
1748 , recS_bind_ty :: PostTc idR Type -- S in (>>=) :: Q -> (R -> S) -> T
1749
1750 -- These fields are only valid after typechecking
1751 , recS_later_rets :: [PostTcExpr] -- (only used in the arrow version)
1752 , recS_rec_rets :: [PostTcExpr] -- These expressions correspond 1-to-1
1753 -- with recS_later_ids and recS_rec_ids,
1754 -- and are the expressions that should be
1755 -- returned by the recursion.
1756 -- They may not quite be the Ids themselves,
1757 -- because the Id may be *polymorphic*, but
1758 -- the returned thing has to be *monomorphic*,
1759 -- so they may be type applications
1760
1761 , recS_ret_ty :: PostTc idR Type -- The type of
1762 -- do { stmts; return (a,b,c) }
1763 -- With rebindable syntax the type might not
1764 -- be quite as simple as (m (tya, tyb, tyc)).
1765 }
1766 deriving instance (Data body, DataId idL, DataId idR)
1767 => Data (StmtLR idL idR body)
1768
1769 data TransForm -- The 'f' below is the 'using' function, 'e' is the by function
1770 = ThenForm -- then f or then f by e (depending on trS_by)
1771 | GroupForm -- then group using f or then group by e using f (depending on trS_by)
1772 deriving Data
1773
1774 -- | Parenthesised Statement Block
1775 data ParStmtBlock idL idR
1776 = ParStmtBlock
1777 [ExprLStmt idL]
1778 [IdP idR] -- The variables to be returned
1779 (SyntaxExpr idR) -- The return operator
1780 deriving instance (DataId idL, DataId idR) => Data (ParStmtBlock idL idR)
1781
1782 -- | Applicative Argument
1783 data ApplicativeArg idL idR
1784 = ApplicativeArgOne -- A single statement (BindStmt or BodyStmt)
1785 (LPat idL) -- WildPat if it was a BodyStmt (see below)
1786 (LHsExpr idL)
1787 Bool -- True <=> was a BodyStmt
1788 -- False <=> was a BindStmt
1789 -- See Note [Applicative BodyStmt]
1790
1791 | ApplicativeArgMany -- do { stmts; return vars }
1792 [ExprLStmt idL] -- stmts
1793 (HsExpr idL) -- return (v1,..,vn), or just (v1,..,vn)
1794 (LPat idL) -- (v1,...,vn)
1795
1796 deriving instance (DataId idL, DataId idR) => Data (ApplicativeArg idL idR)
1797
1798 {-
1799 Note [The type of bind in Stmts]
1800 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1801 Some Stmts, notably BindStmt, keep the (>>=) bind operator.
1802 We do NOT assume that it has type
1803 (>>=) :: m a -> (a -> m b) -> m b
1804 In some cases (see Trac #303, #1537) it might have a more
1805 exotic type, such as
1806 (>>=) :: m i j a -> (a -> m j k b) -> m i k b
1807 So we must be careful not to make assumptions about the type.
1808 In particular, the monad may not be uniform throughout.
1809
1810 Note [TransStmt binder map]
1811 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1812 The [(idR,idR)] in a TransStmt behaves as follows:
1813
1814 * Before renaming: []
1815
1816 * After renaming:
1817 [ (x27,x27), ..., (z35,z35) ]
1818 These are the variables
1819 bound by the stmts to the left of the 'group'
1820 and used either in the 'by' clause,
1821 or in the stmts following the 'group'
1822 Each item is a pair of identical variables.
1823
1824 * After typechecking:
1825 [ (x27:Int, x27:[Int]), ..., (z35:Bool, z35:[Bool]) ]
1826 Each pair has the same unique, but different *types*.
1827
1828 Note [BodyStmt]
1829 ~~~~~~~~~~~~~~~
1830 BodyStmts are a bit tricky, because what they mean
1831 depends on the context. Consider the following contexts:
1832
1833 A do expression of type (m res_ty)
1834 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1835 * BodyStmt E any_ty: do { ....; E; ... }
1836 E :: m any_ty
1837 Translation: E >> ...
1838
1839 A list comprehensions of type [elt_ty]
1840 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1841 * BodyStmt E Bool: [ .. | .... E ]
1842 [ .. | ..., E, ... ]
1843 [ .. | .... | ..., E | ... ]
1844 E :: Bool
1845 Translation: if E then fail else ...
1846
1847 A guard list, guarding a RHS of type rhs_ty
1848 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1849 * BodyStmt E BooParStmtBlockl: f x | ..., E, ... = ...rhs...
1850 E :: Bool
1851 Translation: if E then fail else ...
1852
1853 A monad comprehension of type (m res_ty)
1854 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1855 * BodyStmt E Bool: [ .. | .... E ]
1856 E :: Bool
1857 Translation: guard E >> ...
1858
1859 Array comprehensions are handled like list comprehensions.
1860
1861 Note [How RecStmt works]
1862 ~~~~~~~~~~~~~~~~~~~~~~~~
1863 Example:
1864 HsDo [ BindStmt x ex
1865
1866 , RecStmt { recS_rec_ids = [a, c]
1867 , recS_stmts = [ BindStmt b (return (a,c))
1868 , LetStmt a = ...b...
1869 , BindStmt c ec ]
1870 , recS_later_ids = [a, b]
1871
1872 , return (a b) ]
1873
1874 Here, the RecStmt binds a,b,c; but
1875 - Only a,b are used in the stmts *following* the RecStmt,
1876 - Only a,c are used in the stmts *inside* the RecStmt
1877 *before* their bindings
1878
1879 Why do we need *both* rec_ids and later_ids? For monads they could be
1880 combined into a single set of variables, but not for arrows. That
1881 follows from the types of the respective feedback operators:
1882
1883 mfix :: MonadFix m => (a -> m a) -> m a
1884 loop :: ArrowLoop a => a (b,d) (c,d) -> a b c
1885
1886 * For mfix, the 'a' covers the union of the later_ids and the rec_ids
1887 * For 'loop', 'c' is the later_ids and 'd' is the rec_ids
1888
1889 Note [Typing a RecStmt]
1890 ~~~~~~~~~~~~~~~~~~~~~~~
1891 A (RecStmt stmts) types as if you had written
1892
1893 (v1,..,vn, _, ..., _) <- mfix (\~(_, ..., _, r1, ..., rm) ->
1894 do { stmts
1895 ; return (v1,..vn, r1, ..., rm) })
1896
1897 where v1..vn are the later_ids
1898 r1..rm are the rec_ids
1899
1900 Note [Monad Comprehensions]
1901 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1902 Monad comprehensions require separate functions like 'return' and
1903 '>>=' for desugaring. These functions are stored in the statements
1904 used in monad comprehensions. For example, the 'return' of the 'LastStmt'
1905 expression is used to lift the body of the monad comprehension:
1906
1907 [ body | stmts ]
1908 =>
1909 stmts >>= \bndrs -> return body
1910
1911 In transform and grouping statements ('then ..' and 'then group ..') the
1912 'return' function is required for nested monad comprehensions, for example:
1913
1914 [ body | stmts, then f, rest ]
1915 =>
1916 f [ env | stmts ] >>= \bndrs -> [ body | rest ]
1917
1918 BodyStmts require the 'Control.Monad.guard' function for boolean
1919 expressions:
1920
1921 [ body | exp, stmts ]
1922 =>
1923 guard exp >> [ body | stmts ]
1924
1925 Parallel statements require the 'Control.Monad.Zip.mzip' function:
1926
1927 [ body | stmts1 | stmts2 | .. ]
1928 =>
1929 mzip stmts1 (mzip stmts2 (..)) >>= \(bndrs1, (bndrs2, ..)) -> return body
1930
1931 In any other context than 'MonadComp', the fields for most of these
1932 'SyntaxExpr's stay bottom.
1933
1934
1935 Note [Applicative BodyStmt]
1936
1937 (#12143) For the purposes of ApplicativeDo, we treat any BodyStmt
1938 as if it was a BindStmt with a wildcard pattern. For example,
1939
1940 do
1941 x <- A
1942 B
1943 return x
1944
1945 is transformed as if it were
1946
1947 do
1948 x <- A
1949 _ <- B
1950 return x
1951
1952 so it transforms to
1953
1954 (\(x,_) -> x) <$> A <*> B
1955
1956 But we have to remember when we treat a BodyStmt like a BindStmt,
1957 because in error messages we want to emit the original syntax the user
1958 wrote, not our internal representation. So ApplicativeArgOne has a
1959 Bool flag that is True when the original statement was a BodyStmt, so
1960 that we can pretty-print it correctly.
1961 -}
1962
1963 instance (SourceTextX idL, OutputableBndrId idL)
1964 => Outputable (ParStmtBlock idL idR) where
1965 ppr (ParStmtBlock stmts _ _) = interpp'SP stmts
1966
1967 instance (SourceTextX idL, SourceTextX idR,
1968 OutputableBndrId idL, OutputableBndrId idR, Outputable body)
1969 => Outputable (StmtLR idL idR body) where
1970 ppr stmt = pprStmt stmt
1971
1972 pprStmt :: forall idL idR body . (SourceTextX idL, SourceTextX idR,
1973 OutputableBndrId idL, OutputableBndrId idR,
1974 Outputable body)
1975 => (StmtLR idL idR body) -> SDoc
1976 pprStmt (LastStmt expr ret_stripped _)
1977 = whenPprDebug (text "[last]") <+>
1978 (if ret_stripped then text "return" else empty) <+>
1979 ppr expr
1980 pprStmt (BindStmt pat expr _ _ _) = hsep [ppr pat, larrow, ppr expr]
1981 pprStmt (LetStmt (L _ binds)) = hsep [text "let", pprBinds binds]
1982 pprStmt (BodyStmt expr _ _ _) = ppr expr
1983 pprStmt (ParStmt stmtss _ _ _) = sep (punctuate (text " | ") (map ppr stmtss))
1984
1985 pprStmt (TransStmt { trS_stmts = stmts, trS_by = by
1986 , trS_using = using, trS_form = form })
1987 = sep $ punctuate comma (map ppr stmts ++ [pprTransStmt by using form])
1988
1989 pprStmt (RecStmt { recS_stmts = segment, recS_rec_ids = rec_ids
1990 , recS_later_ids = later_ids })
1991 = text "rec" <+>
1992 vcat [ ppr_do_stmts segment
1993 , whenPprDebug (vcat [ text "rec_ids=" <> ppr rec_ids
1994 , text "later_ids=" <> ppr later_ids])]
1995
1996 pprStmt (ApplicativeStmt args mb_join _)
1997 = getPprStyle $ \style ->
1998 if userStyle style
1999 then pp_for_user
2000 else pp_debug
2001 where
2002 -- make all the Applicative stuff invisible in error messages by
2003 -- flattening the whole ApplicativeStmt nest back to a sequence
2004 -- of statements.
2005 pp_for_user = vcat $ concatMap flattenArg args
2006
2007 -- ppr directly rather than transforming here, because we need to
2008 -- inject a "return" which is hard when we're polymorphic in the id
2009 -- type.
2010 flattenStmt :: ExprLStmt idL -> [SDoc]
2011 flattenStmt (L _ (ApplicativeStmt args _ _)) = concatMap flattenArg args
2012 flattenStmt stmt = [ppr stmt]
2013
2014 flattenArg (_, ApplicativeArgOne pat expr isBody)
2015 | isBody = -- See Note [Applicative BodyStmt]
2016 [ppr (BodyStmt expr noSyntaxExpr noSyntaxExpr (panic "pprStmt")
2017 :: ExprStmt idL)]
2018 | otherwise =
2019 [ppr (BindStmt pat expr noSyntaxExpr noSyntaxExpr (panic "pprStmt")
2020 :: ExprStmt idL)]
2021 flattenArg (_, ApplicativeArgMany stmts _ _) =
2022 concatMap flattenStmt stmts
2023
2024 pp_debug =
2025 let
2026 ap_expr = sep (punctuate (text " |") (map pp_arg args))
2027 in
2028 if isNothing mb_join
2029 then ap_expr
2030 else text "join" <+> parens ap_expr
2031
2032 pp_arg (_, ApplicativeArgOne pat expr isBody)
2033 | isBody = -- See Note [Applicative BodyStmt]
2034 ppr (BodyStmt expr noSyntaxExpr noSyntaxExpr (panic "pprStmt")
2035 :: ExprStmt idL)
2036 | otherwise =
2037 ppr (BindStmt pat expr noSyntaxExpr noSyntaxExpr (panic "pprStmt")
2038 :: ExprStmt idL)
2039 pp_arg (_, ApplicativeArgMany stmts return pat) =
2040 ppr pat <+>
2041 text "<-" <+>
2042 ppr (HsDo DoExpr (noLoc
2043 (stmts ++ [noLoc (LastStmt (noLoc return) False noSyntaxExpr)]))
2044 (error "pprStmt"))
2045
2046 pprTransformStmt :: (SourceTextX p, OutputableBndrId p)
2047 => [IdP p] -> LHsExpr p -> Maybe (LHsExpr p) -> SDoc
2048 pprTransformStmt bndrs using by
2049 = sep [ text "then" <+> whenPprDebug (braces (ppr bndrs))
2050 , nest 2 (ppr using)
2051 , nest 2 (pprBy by)]
2052
2053 pprTransStmt :: Outputable body => Maybe body -> body -> TransForm -> SDoc
2054 pprTransStmt by using ThenForm
2055 = sep [ text "then", nest 2 (ppr using), nest 2 (pprBy by)]
2056 pprTransStmt by using GroupForm
2057 = sep [ text "then group", nest 2 (pprBy by), nest 2 (ptext (sLit "using") <+> ppr using)]
2058
2059 pprBy :: Outputable body => Maybe body -> SDoc
2060 pprBy Nothing = empty
2061 pprBy (Just e) = text "by" <+> ppr e
2062
2063 pprDo :: (SourceTextX p, OutputableBndrId p, Outputable body)
2064 => HsStmtContext any -> [LStmt p body] -> SDoc
2065 pprDo DoExpr stmts = text "do" <+> ppr_do_stmts stmts
2066 pprDo GhciStmtCtxt stmts = text "do" <+> ppr_do_stmts stmts
2067 pprDo ArrowExpr stmts = text "do" <+> ppr_do_stmts stmts
2068 pprDo MDoExpr stmts = text "mdo" <+> ppr_do_stmts stmts
2069 pprDo ListComp stmts = brackets $ pprComp stmts
2070 pprDo PArrComp stmts = paBrackets $ pprComp stmts
2071 pprDo MonadComp stmts = brackets $ pprComp stmts
2072 pprDo _ _ = panic "pprDo" -- PatGuard, ParStmtCxt
2073
2074 ppr_do_stmts :: (SourceTextX idL, SourceTextX idR,
2075 OutputableBndrId idL, OutputableBndrId idR, Outputable body)
2076 => [LStmtLR idL idR body] -> SDoc
2077 -- Print a bunch of do stmts
2078 ppr_do_stmts stmts = pprDeeperList vcat (map ppr stmts)
2079
2080 pprComp :: (SourceTextX p, OutputableBndrId p, Outputable body)
2081 => [LStmt p body] -> SDoc
2082 pprComp quals -- Prints: body | qual1, ..., qualn
2083 | Just (initStmts, L _ (LastStmt body _ _)) <- snocView quals
2084 = if null initStmts
2085 -- If there are no statements in a list comprehension besides the last
2086 -- one, we simply treat it like a normal list. This does arise
2087 -- occasionally in code that GHC generates, e.g., in implementations of
2088 -- 'range' for derived 'Ix' instances for product datatypes with exactly
2089 -- one constructor (e.g., see Trac #12583).
2090 then ppr body
2091 else hang (ppr body <+> vbar) 2 (pprQuals initStmts)
2092 | otherwise
2093 = pprPanic "pprComp" (pprQuals quals)
2094
2095 pprQuals :: (SourceTextX p, OutputableBndrId p, Outputable body)
2096 => [LStmt p body] -> SDoc
2097 -- Show list comprehension qualifiers separated by commas
2098 pprQuals quals = interpp'SP quals
2099
2100 {-
2101 ************************************************************************
2102 * *
2103 Template Haskell quotation brackets
2104 * *
2105 ************************************************************************
2106 -}
2107
2108 -- | Haskell Splice
2109 data HsSplice id
2110 = HsTypedSplice -- $$z or $$(f 4)
2111 SpliceDecoration -- Whether $$( ) variant found, for pretty printing
2112 (IdP id) -- A unique name to identify this splice point
2113 (LHsExpr id) -- See Note [Pending Splices]
2114
2115 | HsUntypedSplice -- $z or $(f 4)
2116 SpliceDecoration -- Whether $( ) variant found, for pretty printing
2117 (IdP id) -- A unique name to identify this splice point
2118 (LHsExpr id) -- See Note [Pending Splices]
2119
2120 | HsQuasiQuote -- See Note [Quasi-quote overview] in TcSplice
2121 (IdP id) -- Splice point
2122 (IdP id) -- Quoter
2123 SrcSpan -- The span of the enclosed string
2124 FastString -- The enclosed string
2125
2126 | HsSpliced -- See Note [Delaying modFinalizers in untyped splices] in
2127 -- RnSplice.
2128 -- This is the result of splicing a splice. It is produced by
2129 -- the renamer and consumed by the typechecker. It lives only
2130 -- between the two.
2131 ThModFinalizers -- TH finalizers produced by the splice.
2132 (HsSplicedThing id) -- The result of splicing
2133 deriving Typeable
2134 deriving instance (DataId id) => Data (HsSplice id)
2135
2136 -- | A splice can appear with various decorations wrapped around it. This data
2137 -- type captures explicitly how it was originally written, for use in the pretty
2138 -- printer.
2139 data SpliceDecoration
2140 = HasParens -- ^ $( splice ) or $$( splice )
2141 | HasDollar -- ^ $splice or $$splice
2142 | NoParens -- ^ bare splice
2143 deriving (Data, Eq, Show)
2144
2145 instance Outputable SpliceDecoration where
2146 ppr x = text $ show x
2147
2148
2149 isTypedSplice :: HsSplice id -> Bool
2150 isTypedSplice (HsTypedSplice {}) = True
2151 isTypedSplice _ = False -- Quasi-quotes are untyped splices
2152
2153 -- | Finalizers produced by a splice with
2154 -- 'Language.Haskell.TH.Syntax.addModFinalizer'
2155 --
2156 -- See Note [Delaying modFinalizers in untyped splices] in RnSplice. For how
2157 -- this is used.
2158 --
2159 newtype ThModFinalizers = ThModFinalizers [ForeignRef (TH.Q ())]
2160
2161 -- A Data instance which ignores the argument of 'ThModFinalizers'.
2162 instance Data ThModFinalizers where
2163 gunfold _ z _ = z $ ThModFinalizers []
2164 toConstr a = mkConstr (dataTypeOf a) "ThModFinalizers" [] Data.Prefix
2165 dataTypeOf a = mkDataType "HsExpr.ThModFinalizers" [toConstr a]
2166
2167 -- | Haskell Spliced Thing
2168 --
2169 -- Values that can result from running a splice.
2170 data HsSplicedThing id
2171 = HsSplicedExpr (HsExpr id) -- ^ Haskell Spliced Expression
2172 | HsSplicedTy (HsType id) -- ^ Haskell Spliced Type
2173 | HsSplicedPat (Pat id) -- ^ Haskell Spliced Pattern
2174 deriving Typeable
2175
2176 deriving instance (DataId id) => Data (HsSplicedThing id)
2177
2178 -- See Note [Pending Splices]
2179 type SplicePointName = Name
2180
2181 -- | Pending Renamer Splice
2182 data PendingRnSplice
2183 -- AZ:TODO: The hard-coded GhcRn feels wrong. How to force the PostRn?
2184 = PendingRnSplice UntypedSpliceFlavour SplicePointName (LHsExpr GhcRn)
2185 deriving Data
2186
2187 data UntypedSpliceFlavour
2188 = UntypedExpSplice
2189 | UntypedPatSplice
2190 | UntypedTypeSplice
2191 | UntypedDeclSplice
2192 deriving Data
2193
2194 -- | Pending Type-checker Splice
2195 data PendingTcSplice
2196 -- AZ:TODO: The hard-coded GhcTc feels wrong. How to force the PostTc?
2197 = PendingTcSplice SplicePointName (LHsExpr GhcTc)
2198 deriving Data
2199
2200
2201 {-
2202 Note [Pending Splices]
2203 ~~~~~~~~~~~~~~~~~~~~~~
2204 When we rename an untyped bracket, we name and lift out all the nested
2205 splices, so that when the typechecker hits the bracket, it can
2206 typecheck those nested splices without having to walk over the untyped
2207 bracket code. So for example
2208 [| f $(g x) |]
2209 looks like
2210
2211 HsBracket (HsApp (HsVar "f") (HsSpliceE _ (g x)))
2212
2213 which the renamer rewrites to
2214
2215 HsRnBracketOut (HsApp (HsVar f) (HsSpliceE sn (g x)))
2216 [PendingRnSplice UntypedExpSplice sn (g x)]
2217
2218 * The 'sn' is the Name of the splice point, the SplicePointName
2219
2220 * The PendingRnExpSplice gives the splice that splice-point name maps to;
2221 and the typechecker can now conveniently find these sub-expressions
2222
2223 * The other copy of the splice, in the second argument of HsSpliceE
2224 in the renamed first arg of HsRnBracketOut
2225 is used only for pretty printing
2226
2227 There are four varieties of pending splices generated by the renamer,
2228 distinguished by their UntypedSpliceFlavour
2229
2230 * Pending expression splices (UntypedExpSplice), e.g.,
2231 [|$(f x) + 2|]
2232
2233 UntypedExpSplice is also used for
2234 * quasi-quotes, where the pending expression expands to
2235 $(quoter "...blah...")
2236 (see RnSplice.makePending, HsQuasiQuote case)
2237
2238 * cross-stage lifting, where the pending expression expands to
2239 $(lift x)
2240 (see RnSplice.checkCrossStageLifting)
2241
2242 * Pending pattern splices (UntypedPatSplice), e.g.,
2243 [| \$(f x) -> x |]
2244
2245 * Pending type splices (UntypedTypeSplice), e.g.,
2246 [| f :: $(g x) |]
2247
2248 * Pending declaration (UntypedDeclSplice), e.g.,
2249 [| let $(f x) in ... |]
2250
2251 There is a fifth variety of pending splice, which is generated by the type
2252 checker:
2253
2254 * Pending *typed* expression splices, (PendingTcSplice), e.g.,
2255 [||1 + $$(f 2)||]
2256
2257 It would be possible to eliminate HsRnBracketOut and use HsBracketOut for the
2258 output of the renamer. However, when pretty printing the output of the renamer,
2259 e.g., in a type error message, we *do not* want to print out the pending
2260 splices. In contrast, when pretty printing the output of the type checker, we
2261 *do* want to print the pending splices. So splitting them up seems to make
2262 sense, although I hate to add another constructor to HsExpr.
2263 -}
2264
2265 instance (SourceTextX p, OutputableBndrId p)
2266 => Outputable (HsSplicedThing p) where
2267 ppr (HsSplicedExpr e) = ppr_expr e
2268 ppr (HsSplicedTy t) = ppr t
2269 ppr (HsSplicedPat p) = ppr p
2270
2271 instance (SourceTextX p, OutputableBndrId p) => Outputable (HsSplice p) where
2272 ppr s = pprSplice s
2273
2274 pprPendingSplice :: (SourceTextX p, OutputableBndrId p)
2275 => SplicePointName -> LHsExpr p -> SDoc
2276 pprPendingSplice n e = angleBrackets (ppr n <> comma <+> ppr e)
2277
2278 pprSpliceDecl :: (SourceTextX p, OutputableBndrId p)
2279 => HsSplice p -> SpliceExplicitFlag -> SDoc
2280 pprSpliceDecl e@HsQuasiQuote{} _ = pprSplice e
2281 pprSpliceDecl e ExplicitSplice = text "$(" <> ppr_splice_decl e <> text ")"
2282 pprSpliceDecl e ImplicitSplice = ppr_splice_decl e
2283
2284 ppr_splice_decl :: (SourceTextX p, OutputableBndrId p) => HsSplice p -> SDoc
2285 ppr_splice_decl (HsUntypedSplice _ n e) = ppr_splice empty n e empty
2286 ppr_splice_decl e = pprSplice e
2287
2288 pprSplice :: (SourceTextX p, OutputableBndrId p) => HsSplice p -> SDoc
2289 pprSplice (HsTypedSplice HasParens n e)
2290 = ppr_splice (text "$$(") n e (text ")")
2291 pprSplice (HsTypedSplice HasDollar n e)
2292 = ppr_splice (text "$$") n e empty
2293 pprSplice (HsTypedSplice NoParens n e)
2294 = ppr_splice empty n e empty
2295 pprSplice (HsUntypedSplice HasParens n e)
2296 = ppr_splice (text "$(") n e (text ")")
2297 pprSplice (HsUntypedSplice HasDollar n e)
2298 = ppr_splice (text "$") n e empty
2299 pprSplice (HsUntypedSplice NoParens n e)
2300 = ppr_splice empty n e empty
2301 pprSplice (HsQuasiQuote n q _ s) = ppr_quasi n q s
2302 pprSplice (HsSpliced _ thing) = ppr thing
2303
2304 ppr_quasi :: OutputableBndr p => p -> p -> FastString -> SDoc
2305 ppr_quasi n quoter quote = whenPprDebug (brackets (ppr n)) <>
2306 char '[' <> ppr quoter <> vbar <>
2307 ppr quote <> text "|]"
2308
2309 ppr_splice :: (SourceTextX p, OutputableBndrId p)
2310 => SDoc -> (IdP p) -> LHsExpr p -> SDoc -> SDoc
2311 ppr_splice herald n e trail
2312 = herald <> whenPprDebug (brackets (ppr n)) <> ppr e <> trail
2313
2314 -- | Haskell Bracket
2315 data HsBracket p = ExpBr (LHsExpr p) -- [| expr |]
2316 | PatBr (LPat p) -- [p| pat |]
2317 | DecBrL [LHsDecl p] -- [d| decls |]; result of parser
2318 | DecBrG (HsGroup p) -- [d| decls |]; result of renamer
2319 | TypBr (LHsType p) -- [t| type |]
2320 | VarBr Bool (IdP p) -- True: 'x, False: ''T
2321 -- (The Bool flag is used only in pprHsBracket)
2322 | TExpBr (LHsExpr p) -- [|| expr ||]
2323 deriving instance (DataId p) => Data (HsBracket p)
2324
2325 isTypedBracket :: HsBracket id -> Bool
2326 isTypedBracket (TExpBr {}) = True
2327 isTypedBracket _ = False
2328
2329 instance (SourceTextX p, OutputableBndrId p) => Outputable (HsBracket p) where
2330 ppr = pprHsBracket
2331
2332
2333 pprHsBracket :: (SourceTextX p, OutputableBndrId p) => HsBracket p -> SDoc
2334 pprHsBracket (ExpBr e) = thBrackets empty (ppr e)
2335 pprHsBracket (PatBr p) = thBrackets (char 'p') (ppr p)
2336 pprHsBracket (DecBrG gp) = thBrackets (char 'd') (ppr gp)
2337 pprHsBracket (DecBrL ds) = thBrackets (char 'd') (vcat (map ppr ds))
2338 pprHsBracket (TypBr t) = thBrackets (char 't') (ppr t)
2339 pprHsBracket (VarBr True n)
2340 = char '\'' <> pprPrefixOcc n
2341 pprHsBracket (VarBr False n)
2342 = text "''" <> pprPrefixOcc n
2343 pprHsBracket (TExpBr e) = thTyBrackets (ppr e)
2344
2345 thBrackets :: SDoc -> SDoc -> SDoc
2346 thBrackets pp_kind pp_body = char '[' <> pp_kind <> vbar <+>
2347 pp_body <+> text "|]"
2348
2349 thTyBrackets :: SDoc -> SDoc
2350 thTyBrackets pp_body = text "[||" <+> pp_body <+> ptext (sLit "||]")
2351
2352 instance Outputable PendingRnSplice where
2353 ppr (PendingRnSplice _ n e) = pprPendingSplice n e
2354
2355 instance Outputable PendingTcSplice where
2356 ppr (PendingTcSplice n e) = pprPendingSplice n e
2357
2358 {-
2359 ************************************************************************
2360 * *
2361 \subsection{Enumerations and list comprehensions}
2362 * *
2363 ************************************************************************
2364 -}
2365
2366 -- | Arithmetic Sequence Information
2367 data ArithSeqInfo id
2368 = From (LHsExpr id)
2369 | FromThen (LHsExpr id)
2370 (LHsExpr id)
2371 | FromTo (LHsExpr id)
2372 (LHsExpr id)
2373 | FromThenTo (LHsExpr id)
2374 (LHsExpr id)
2375 (LHsExpr id)
2376 deriving instance (DataId id) => Data (ArithSeqInfo id)
2377
2378 instance (SourceTextX p, OutputableBndrId p)
2379 => Outputable (ArithSeqInfo p) where
2380 ppr (From e1) = hcat [ppr e1, pp_dotdot]
2381 ppr (FromThen e1 e2) = hcat [ppr e1, comma, space, ppr e2, pp_dotdot]
2382 ppr (FromTo e1 e3) = hcat [ppr e1, pp_dotdot, ppr e3]
2383 ppr (FromThenTo e1 e2 e3)
2384 = hcat [ppr e1, comma, space, ppr e2, pp_dotdot, ppr e3]
2385
2386 pp_dotdot :: SDoc
2387 pp_dotdot = text " .. "
2388
2389 {-
2390 ************************************************************************
2391 * *
2392 \subsection{HsMatchCtxt}
2393 * *
2394 ************************************************************************
2395 -}
2396
2397 -- | Haskell Match Context
2398 --
2399 -- Context of a pattern match. This is more subtle than it would seem. See Note
2400 -- [Varieties of pattern matches].
2401 data HsMatchContext id -- Not an extensible tag
2402 = FunRhs { mc_fun :: Located id -- ^ function binder of @f@
2403 , mc_fixity :: LexicalFixity -- ^ fixing of @f@
2404 , mc_strictness :: SrcStrictness -- ^ was @f@ banged?
2405 -- See Note [FunBind vs PatBind]
2406 }
2407 -- ^A pattern matching on an argument of a
2408 -- function binding
2409 | LambdaExpr -- ^Patterns of a lambda
2410 | CaseAlt -- ^Patterns and guards on a case alternative
2411 | IfAlt -- ^Guards of a multi-way if alternative
2412 | ProcExpr -- ^Patterns of a proc
2413 | PatBindRhs -- ^A pattern binding eg [y] <- e = e
2414
2415 | RecUpd -- ^Record update [used only in DsExpr to
2416 -- tell matchWrapper what sort of
2417 -- runtime error message to generate]
2418
2419 | StmtCtxt (HsStmtContext id) -- ^Pattern of a do-stmt, list comprehension,
2420 -- pattern guard, etc
2421
2422 | ThPatSplice -- ^A Template Haskell pattern splice
2423 | ThPatQuote -- ^A Template Haskell pattern quotation [p| (a,b) |]
2424 | PatSyn -- ^A pattern synonym declaration
2425 deriving Functor
2426 deriving instance (Data id) => Data (HsMatchContext id)
2427
2428 instance OutputableBndr id => Outputable (HsMatchContext id) where
2429 ppr m@(FunRhs{}) = text "FunRhs" <+> ppr (mc_fun m) <+> ppr (mc_fixity m)
2430 ppr LambdaExpr = text "LambdaExpr"
2431 ppr CaseAlt = text "CaseAlt"
2432 ppr IfAlt = text "IfAlt"
2433 ppr ProcExpr = text "ProcExpr"
2434 ppr PatBindRhs = text "PatBindRhs"
2435 ppr RecUpd = text "RecUpd"
2436 ppr (StmtCtxt _) = text "StmtCtxt _"
2437 ppr ThPatSplice = text "ThPatSplice"
2438 ppr ThPatQuote = text "ThPatQuote"
2439 ppr PatSyn = text "PatSyn"
2440
2441 isPatSynCtxt :: HsMatchContext id -> Bool
2442 isPatSynCtxt ctxt =
2443 case ctxt of
2444 PatSyn -> True
2445 _ -> False
2446
2447 -- | Haskell Statement Context. It expects to be parameterised with one of
2448 -- 'RdrName', 'Name' or 'Id'
2449 data HsStmtContext id
2450 = ListComp
2451 | MonadComp
2452 | PArrComp -- ^Parallel array comprehension
2453
2454 | DoExpr -- ^do { ... }
2455 | MDoExpr -- ^mdo { ... } ie recursive do-expression
2456 | ArrowExpr -- ^do-notation in an arrow-command context
2457
2458 | GhciStmtCtxt -- ^A command-line Stmt in GHCi pat <- rhs
2459 | PatGuard (HsMatchContext id) -- ^Pattern guard for specified thing
2460 | ParStmtCtxt (HsStmtContext id) -- ^A branch of a parallel stmt
2461 | TransStmtCtxt (HsStmtContext id) -- ^A branch of a transform stmt
2462 deriving Functor
2463 deriving instance (Data id) => Data (HsStmtContext id)
2464
2465 isListCompExpr :: HsStmtContext id -> Bool
2466 -- Uses syntax [ e | quals ]
2467 isListCompExpr ListComp = True
2468 isListCompExpr PArrComp = True
2469 isListCompExpr MonadComp = True
2470 isListCompExpr (ParStmtCtxt c) = isListCompExpr c
2471 isListCompExpr (TransStmtCtxt c) = isListCompExpr c
2472 isListCompExpr _ = False
2473
2474 -- | Should pattern match failure in a 'HsStmtContext' be desugared using
2475 -- 'MonadFail'?
2476 isMonadFailStmtContext :: HsStmtContext id -> Bool
2477 isMonadFailStmtContext MonadComp = True
2478 isMonadFailStmtContext DoExpr = True
2479 isMonadFailStmtContext MDoExpr = True
2480 isMonadFailStmtContext GhciStmtCtxt = True
2481 isMonadFailStmtContext (ParStmtCtxt ctxt) = isMonadFailStmtContext ctxt
2482 isMonadFailStmtContext (TransStmtCtxt ctxt) = isMonadFailStmtContext ctxt
2483 isMonadFailStmtContext _ = False -- ListComp, PArrComp, PatGuard, ArrowExpr
2484
2485 matchSeparator :: HsMatchContext id -> SDoc
2486 matchSeparator (FunRhs {}) = text "="
2487 matchSeparator CaseAlt = text "->"
2488 matchSeparator IfAlt = text "->"
2489 matchSeparator LambdaExpr = text "->"
2490 matchSeparator ProcExpr = text "->"
2491 matchSeparator PatBindRhs = text "="
2492 matchSeparator (StmtCtxt _) = text "<-"
2493 matchSeparator RecUpd = text "=" -- This can be printed by the pattern
2494 -- match checker trace
2495 matchSeparator ThPatSplice = panic "unused"
2496 matchSeparator ThPatQuote = panic "unused"
2497 matchSeparator PatSyn = panic "unused"
2498
2499 pprMatchContext :: (Outputable (NameOrRdrName id),Outputable id)
2500 => HsMatchContext id -> SDoc
2501 pprMatchContext ctxt
2502 | want_an ctxt = text "an" <+> pprMatchContextNoun ctxt
2503 | otherwise = text "a" <+> pprMatchContextNoun ctxt
2504 where
2505 want_an (FunRhs {}) = True -- Use "an" in front
2506 want_an ProcExpr = True
2507 want_an _ = False
2508
2509 pprMatchContextNoun :: (Outputable (NameOrRdrName id),Outputable id)
2510 => HsMatchContext id -> SDoc
2511 pprMatchContextNoun (FunRhs {mc_fun=L _ fun})
2512 = text "equation for"
2513 <+> quotes (ppr fun)
2514 pprMatchContextNoun CaseAlt = text "case alternative"
2515 pprMatchContextNoun IfAlt = text "multi-way if alternative"
2516 pprMatchContextNoun RecUpd = text "record-update construct"
2517 pprMatchContextNoun ThPatSplice = text "Template Haskell pattern splice"
2518 pprMatchContextNoun ThPatQuote = text "Template Haskell pattern quotation"
2519 pprMatchContextNoun PatBindRhs = text "pattern binding"
2520 pprMatchContextNoun LambdaExpr = text "lambda abstraction"
2521 pprMatchContextNoun ProcExpr = text "arrow abstraction"
2522 pprMatchContextNoun (StmtCtxt ctxt) = text "pattern binding in"
2523 $$ pprStmtContext ctxt
2524 pprMatchContextNoun PatSyn = text "pattern synonym declaration"
2525
2526 -----------------
2527 pprAStmtContext, pprStmtContext :: (Outputable id,
2528 Outputable (NameOrRdrName id))
2529 => HsStmtContext id -> SDoc
2530 pprAStmtContext ctxt = article <+> pprStmtContext ctxt
2531 where
2532 pp_an = text "an"
2533 pp_a = text "a"
2534 article = case ctxt of
2535 MDoExpr -> pp_an
2536 PArrComp -> pp_an
2537 GhciStmtCtxt -> pp_an
2538 _ -> pp_a
2539
2540
2541 -----------------
2542 pprStmtContext GhciStmtCtxt = text "interactive GHCi command"
2543 pprStmtContext DoExpr = text "'do' block"
2544 pprStmtContext MDoExpr = text "'mdo' block"
2545 pprStmtContext ArrowExpr = text "'do' block in an arrow command"
2546 pprStmtContext ListComp = text "list comprehension"
2547 pprStmtContext MonadComp = text "monad comprehension"
2548 pprStmtContext PArrComp = text "array comprehension"
2549 pprStmtContext (PatGuard ctxt) = text "pattern guard for" $$ pprMatchContext ctxt
2550
2551 -- Drop the inner contexts when reporting errors, else we get
2552 -- Unexpected transform statement
2553 -- in a transformed branch of
2554 -- transformed branch of
2555 -- transformed branch of monad comprehension
2556 pprStmtContext (ParStmtCtxt c) =
2557 ifPprDebug (sep [text "parallel branch of", pprAStmtContext c])
2558 (pprStmtContext c)
2559 pprStmtContext (TransStmtCtxt c) =
2560 ifPprDebug (sep [text "transformed branch of", pprAStmtContext c])
2561 (pprStmtContext c)
2562
2563 instance (Outputable p, Outputable (NameOrRdrName p))
2564 => Outputable (HsStmtContext p) where
2565 ppr = pprStmtContext
2566
2567 -- Used to generate the string for a *runtime* error message
2568 matchContextErrString :: Outputable id
2569 => HsMatchContext id -> SDoc
2570 matchContextErrString (FunRhs{mc_fun=L _ fun}) = text "function" <+> ppr fun
2571 matchContextErrString CaseAlt = text "case"
2572 matchContextErrString IfAlt = text "multi-way if"
2573 matchContextErrString PatBindRhs = text "pattern binding"
2574 matchContextErrString RecUpd = text "record update"
2575 matchContextErrString LambdaExpr = text "lambda"
2576 matchContextErrString ProcExpr = text "proc"
2577 matchContextErrString ThPatSplice = panic "matchContextErrString" -- Not used at runtime
2578 matchContextErrString ThPatQuote = panic "matchContextErrString" -- Not used at runtime
2579 matchContextErrString PatSyn = panic "matchContextErrString" -- Not used at runtime
2580 matchContextErrString (StmtCtxt (ParStmtCtxt c)) = matchContextErrString (StmtCtxt c)
2581 matchContextErrString (StmtCtxt (TransStmtCtxt c)) = matchContextErrString (StmtCtxt c)
2582 matchContextErrString (StmtCtxt (PatGuard _)) = text "pattern guard"
2583 matchContextErrString (StmtCtxt GhciStmtCtxt) = text "interactive GHCi command"
2584 matchContextErrString (StmtCtxt DoExpr) = text "'do' block"
2585 matchContextErrString (StmtCtxt ArrowExpr) = text "'do' block"
2586 matchContextErrString (StmtCtxt MDoExpr) = text "'mdo' block"
2587 matchContextErrString (StmtCtxt ListComp) = text "list comprehension"
2588 matchContextErrString (StmtCtxt MonadComp) = text "monad comprehension"
2589 matchContextErrString (StmtCtxt PArrComp) = text "array comprehension"
2590
2591 pprMatchInCtxt :: (SourceTextX idR, OutputableBndrId idR,
2592 -- TODO:AZ these constraints do not make sense
2593 Outputable (NameOrRdrName (NameOrRdrName (IdP idR))),
2594 Outputable body)
2595 => Match idR body -> SDoc
2596 pprMatchInCtxt match = hang (text "In" <+> pprMatchContext (m_ctxt match)
2597 <> colon)
2598 4 (pprMatch match)
2599
2600 pprStmtInCtxt :: (SourceTextX idL, SourceTextX idR,
2601 OutputableBndrId idL, OutputableBndrId idR,
2602 Outputable body)
2603 => HsStmtContext (IdP idL) -> StmtLR idL idR body -> SDoc
2604 pprStmtInCtxt ctxt (LastStmt e _ _)
2605 | isListCompExpr ctxt -- For [ e | .. ], do not mutter about "stmts"
2606 = hang (text "In the expression:") 2 (ppr e)
2607
2608 pprStmtInCtxt ctxt stmt
2609 = hang (text "In a stmt of" <+> pprAStmtContext ctxt <> colon)
2610 2 (ppr_stmt stmt)
2611 where
2612 -- For Group and Transform Stmts, don't print the nested stmts!
2613 ppr_stmt (TransStmt { trS_by = by, trS_using = using
2614 , trS_form = form }) = pprTransStmt by using form
2615 ppr_stmt stmt = pprStmt stmt