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