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