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