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