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