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