9fd90b6c1391f81c08fe62b571f8ea52a46a3b7d
[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
13 -- | Abstract Haskell syntax for expressions.
14 module HsExpr where
15
16 #include "HsVersions.h"
17
18 -- friends:
19 import HsDecls
20 import HsPat
21 import HsLit
22 import PlaceHolder ( PostTc,PostRn,DataId )
23 import HsTypes
24 import HsBinds
25
26 -- others:
27 import TcEvidence
28 import CoreSyn
29 import Var
30 import RdrName
31 import Name
32 import BasicTypes
33 import DataCon
34 import SrcLoc
35 import Util
36 import StaticFlags( opt_PprStyle_Debug )
37 import Outputable
38 import FastString
39 import Type
40
41 -- libraries:
42 import Data.Data hiding (Fixity)
43
44 {-
45 ************************************************************************
46 * *
47 \subsection{Expressions proper}
48 * *
49 ************************************************************************
50 -}
51
52 -- * Expressions proper
53
54 type LHsExpr id = Located (HsExpr id)
55 -- ^ May have 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnComma' when
56 -- in a list
57
58 -- For details on above see note [Api annotations] in ApiAnnotation
59
60 -------------------------
61 -- | PostTcExpr is an evidence expression attached to the syntax tree by the
62 -- type checker (c.f. postTcType).
63 type PostTcExpr = HsExpr Id
64 -- | We use a PostTcTable where there are a bunch of pieces of evidence, more
65 -- than is convenient to keep individually.
66 type PostTcTable = [(Name, PostTcExpr)]
67
68 noPostTcExpr :: PostTcExpr
69 noPostTcExpr = HsLit (HsString "" (fsLit "noPostTcExpr"))
70
71 noPostTcTable :: PostTcTable
72 noPostTcTable = []
73
74 -------------------------
75 -- | SyntaxExpr is like 'PostTcExpr', but it's filled in a little earlier,
76 -- by the renamer. It's used for rebindable syntax.
77 --
78 -- E.g. @(>>=)@ is filled in before the renamer by the appropriate 'Name' for
79 -- @(>>=)@, and then instantiated by the type checker with its type args
80 -- etc
81
82 type SyntaxExpr id = HsExpr id
83
84 noSyntaxExpr :: SyntaxExpr id -- Before renaming, and sometimes after,
85 -- (if the syntax slot makes no sense)
86 noSyntaxExpr = HsLit (HsString "" (fsLit "noSyntaxExpr"))
87
88
89 type CmdSyntaxTable id = [(Name, SyntaxExpr id)]
90 -- See Note [CmdSyntaxTable]
91
92 {-
93 Note [CmdSyntaxtable]
94 ~~~~~~~~~~~~~~~~~~~~~
95 Used only for arrow-syntax stuff (HsCmdTop), the CmdSyntaxTable keeps
96 track of the methods needed for a Cmd.
97
98 * Before the renamer, this list is an empty list
99
100 * After the renamer, it takes the form @[(std_name, HsVar actual_name)]@
101 For example, for the 'arr' method
102 * normal case: (GHC.Control.Arrow.arr, HsVar GHC.Control.Arrow.arr)
103 * with rebindable syntax: (GHC.Control.Arrow.arr, arr_22)
104 where @arr_22@ is whatever 'arr' is in scope
105
106 * After the type checker, it takes the form [(std_name, <expression>)]
107 where <expression> is the evidence for the method. This evidence is
108 instantiated with the class, but is still polymorphic in everything
109 else. For example, in the case of 'arr', the evidence has type
110 forall b c. (b->c) -> a b c
111 where 'a' is the ambient type of the arrow. This polymorphism is
112 important because the desugarer uses the same evidence at multiple
113 different types.
114
115 This is Less Cool than what we normally do for rebindable syntax, which is to
116 make fully-instantiated piece of evidence at every use site. The Cmd way
117 is Less Cool because
118 * The renamer has to predict which methods are needed.
119 See the tedious RnExpr.methodNamesCmd.
120
121 * The desugarer has to know the polymorphic type of the instantiated
122 method. This is checked by Inst.tcSyntaxName, but is less flexible
123 than the rest of rebindable syntax, where the type is less
124 pre-ordained. (And this flexibility is useful; for example we can
125 typecheck do-notation with (>>=) :: m1 a -> (a -> m2 b) -> m2 b.)
126 -}
127
128 -- | A Haskell expression.
129 data HsExpr id
130 = HsVar id -- ^ Variable
131 | HsIPVar HsIPName -- ^ Implicit parameter
132 | HsOverLit (HsOverLit id) -- ^ Overloaded literals
133
134 | HsLit HsLit -- ^ Simple (non-overloaded) literals
135
136 | HsLam (MatchGroup id (LHsExpr id)) -- ^ Lambda abstraction. Currently always a single match
137 --
138 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLam',
139 -- 'ApiAnnotation.AnnRarrow',
140
141 -- For details on above see note [Api annotations] in ApiAnnotation
142
143 | HsLamCase (PostTc id Type) (MatchGroup id (LHsExpr id)) -- ^ Lambda-case
144 --
145 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLam',
146 -- 'ApiAnnotation.AnnCase','ApiAnnotation.AnnOpen',
147 -- 'ApiAnnotation.AnnClose'
148
149 -- For details on above see note [Api annotations] in ApiAnnotation
150
151 | HsApp (LHsExpr id) (LHsExpr id) -- ^ Application
152
153 -- | Operator applications:
154 -- NB Bracketed ops such as (+) come out as Vars.
155
156 -- NB We need an expr for the operator in an OpApp/Section since
157 -- the typechecker may need to apply the operator to a few types.
158
159 | OpApp (LHsExpr id) -- left operand
160 (LHsExpr id) -- operator
161 (PostRn id Fixity) -- Renamer adds fixity; bottom until then
162 (LHsExpr id) -- right operand
163
164 -- | Negation operator. Contains the negated expression and the name
165 -- of 'negate'
166 --
167 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnMinus'
168
169 -- For details on above see note [Api annotations] in ApiAnnotation
170 | NegApp (LHsExpr id)
171 (SyntaxExpr id)
172
173 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@,
174 -- 'ApiAnnotation.AnnClose' @')'@
175
176 -- For details on above see note [Api annotations] in ApiAnnotation
177 | HsPar (LHsExpr id) -- ^ Parenthesised expr; see Note [Parens in HsSyn]
178
179 | SectionL (LHsExpr id) -- operand; see Note [Sections in HsSyn]
180 (LHsExpr id) -- operator
181 | SectionR (LHsExpr id) -- operator; see Note [Sections in HsSyn]
182 (LHsExpr id) -- operand
183
184 -- | Used for explicit tuples and sections thereof
185 --
186 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
187 -- 'ApiAnnotation.AnnClose'
188
189 -- For details on above see note [Api annotations] in ApiAnnotation
190 | ExplicitTuple
191 [LHsTupArg id]
192 Boxity
193
194 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnCase',
195 -- 'ApiAnnotation.AnnOf','ApiAnnotation.AnnOpen' @'{'@,
196 -- 'ApiAnnotation.AnnClose' @'}'@
197
198 -- For details on above see note [Api annotations] in ApiAnnotation
199 | HsCase (LHsExpr id)
200 (MatchGroup id (LHsExpr id))
201
202 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnIf',
203 -- 'ApiAnnotation.AnnSemi',
204 -- 'ApiAnnotation.AnnThen','ApiAnnotation.AnnSemi',
205 -- 'ApiAnnotation.AnnElse',
206
207 -- For details on above see note [Api annotations] in ApiAnnotation
208 | HsIf (Maybe (SyntaxExpr id)) -- cond function
209 -- Nothing => use the built-in 'if'
210 -- See Note [Rebindable if]
211 (LHsExpr id) -- predicate
212 (LHsExpr id) -- then part
213 (LHsExpr id) -- else part
214
215 -- | Multi-way if
216 --
217 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnIf'
218 -- 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose',
219
220 -- For details on above see note [Api annotations] in ApiAnnotation
221 | HsMultiIf (PostTc id Type) [LGRHS id (LHsExpr id)]
222
223 -- | let(rec)
224 --
225 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLet',
226 -- 'ApiAnnotation.AnnOpen' @'{'@,
227 -- 'ApiAnnotation.AnnClose' @'}'@,'ApiAnnotation.AnnIn'
228
229 -- For details on above see note [Api annotations] in ApiAnnotation
230 | HsLet (HsLocalBinds id)
231 (LHsExpr id)
232
233 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDo',
234 -- 'ApiAnnotation.AnnOpen', 'ApiAnnotation.AnnSemi',
235 -- 'ApiAnnotation.AnnVbar',
236 -- 'ApiAnnotation.AnnClose'
237
238 -- For details on above see note [Api annotations] in ApiAnnotation
239 | HsDo (HsStmtContext Name) -- The parameterisation is unimportant
240 -- because in this context we never use
241 -- the PatGuard or ParStmt variant
242 [ExprLStmt id] -- "do":one or more stmts
243 (PostTc id Type) -- Type of the whole expression
244
245 -- | Syntactic list: [a,b,c,...]
246 --
247 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'['@,
248 -- 'ApiAnnotation.AnnClose' @']'@
249
250 -- For details on above see note [Api annotations] in ApiAnnotation
251 | ExplicitList
252 (PostTc id Type) -- Gives type of components of list
253 (Maybe (SyntaxExpr id)) -- For OverloadedLists, the fromListN witness
254 [LHsExpr id]
255
256 -- | Syntactic parallel array: [:e1, ..., en:]
257 --
258 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'[:'@,
259 -- 'ApiAnnotation.AnnDotdot','ApiAnnotation.AnnComma',
260 -- 'ApiAnnotation.AnnVbar'
261 -- 'ApiAnnotation.AnnClose' @':]'@
262
263 -- For details on above see note [Api annotations] in ApiAnnotation
264 | ExplicitPArr
265 (PostTc id Type) -- type of elements of the parallel array
266 [LHsExpr id]
267
268 -- | Record construction
269 --
270 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{'@,
271 -- 'ApiAnnotation.AnnDotdot','ApiAnnotation.AnnClose' @'}'@
272
273 -- For details on above see note [Api annotations] in ApiAnnotation
274 | RecordCon (Located id) -- The constructor. After type checking
275 -- it's the dataConWrapId of the constructor
276 PostTcExpr -- Data con Id applied to type args
277 (HsRecordBinds id)
278
279 -- | Record update
280 --
281 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{'@,
282 -- 'ApiAnnotation.AnnDotdot','ApiAnnotation.AnnClose' @'}'@
283
284 -- For details on above see note [Api annotations] in ApiAnnotation
285 | RecordUpd (LHsExpr id)
286 (HsRecordBinds id)
287 -- (HsMatchGroup Id) -- Filled in by the type checker to be
288 -- -- a match that does the job
289 [DataCon] -- Filled in by the type checker to the
290 -- _non-empty_ list of DataCons that have
291 -- all the upd'd fields
292 [PostTc id Type] -- Argument types of *input* record type
293 [PostTc id Type] -- and *output* record type
294 -- For a type family, the arg types are of the *instance* tycon,
295 -- not the family tycon
296
297 -- | Expression with an explicit type signature. @e :: type@
298 --
299 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDcolon'
300
301 -- For details on above see note [Api annotations] in ApiAnnotation
302 | ExprWithTySig
303 (LHsExpr id)
304 (LHsType id)
305 (PostRn id [Name]) -- After renaming, the list of Names
306 -- contains the named and unnamed
307 -- wildcards brought in scope by the
308 -- signature
309
310 | ExprWithTySigOut -- TRANSLATION
311 (LHsExpr id)
312 (LHsType Name) -- Retain the signature for
313 -- round-tripping purposes
314
315 -- | Arithmetic sequence
316 --
317 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'['@,
318 -- 'ApiAnnotation.AnnComma','ApiAnnotation.AnnDotdot',
319 -- 'ApiAnnotation.AnnClose' @']'@
320
321 -- For details on above see note [Api annotations] in ApiAnnotation
322 | ArithSeq
323 PostTcExpr
324 (Maybe (SyntaxExpr id)) -- For OverloadedLists, the fromList witness
325 (ArithSeqInfo id)
326
327 -- | Arithmetic sequence for parallel array
328 --
329 -- > [:e1..e2:] or [:e1, e2..e3:]
330 --
331 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'[:'@,
332 -- 'ApiAnnotation.AnnComma','ApiAnnotation.AnnDotdot',
333 -- 'ApiAnnotation.AnnVbar',
334 -- 'ApiAnnotation.AnnClose' @':]'@
335
336 -- For details on above see note [Api annotations] in ApiAnnotation
337 | PArrSeq
338 PostTcExpr
339 (ArithSeqInfo id)
340
341 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{-\# SCC'@,
342 -- 'ApiAnnotation.AnnVal' or 'ApiAnnotation.AnnValStr',
343 -- 'ApiAnnotation.AnnClose' @'\#-}'@
344
345 -- For details on above see note [Api annotations] in ApiAnnotation
346 | HsSCC SourceText -- Note [Pragma source text] in BasicTypes
347 FastString -- "set cost centre" SCC pragma
348 (LHsExpr id) -- expr whose cost is to be measured
349
350 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{-\# CORE'@,
351 -- 'ApiAnnotation.AnnVal', 'ApiAnnotation.AnnClose' @'\#-}'@
352
353 -- For details on above see note [Api annotations] in ApiAnnotation
354 | HsCoreAnn SourceText -- Note [Pragma source text] in BasicTypes
355 FastString -- hdaume: core annotation
356 (LHsExpr id)
357
358 -----------------------------------------------------------
359 -- MetaHaskell Extensions
360
361 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
362 -- 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose',
363 -- 'ApiAnnotation.AnnClose'
364
365 -- For details on above see note [Api annotations] in ApiAnnotation
366 | HsBracket (HsBracket id)
367
368 -- See Note [Pending Splices]
369 | HsRnBracketOut
370 (HsBracket Name) -- Output of the renamer is the *original* renamed
371 -- expression, plus
372 [PendingRnSplice] -- _renamed_ splices to be type checked
373
374 | HsTcBracketOut
375 (HsBracket Name) -- Output of the type checker is the *original*
376 -- renamed expression, plus
377 [PendingTcSplice] -- _typechecked_ splices to be
378 -- pasted back in by the desugarer
379
380 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
381 -- 'ApiAnnotation.AnnClose'
382
383 -- For details on above see note [Api annotations] in ApiAnnotation
384 | HsSpliceE Bool -- True <=> typed splice
385 (HsSplice id) -- False <=> untyped
386
387 | HsQuasiQuoteE (HsQuasiQuote id)
388 -- See Note [Quasi-quote overview] in TcSplice
389
390 -----------------------------------------------------------
391 -- Arrow notation extension
392
393 -- | @proc@ notation for Arrows
394 --
395 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnProc',
396 -- 'ApiAnnotation.AnnRarrow'
397
398 -- For details on above see note [Api annotations] in ApiAnnotation
399 | HsProc (LPat id) -- arrow abstraction, proc
400 (LHsCmdTop id) -- body of the abstraction
401 -- always has an empty stack
402
403 ---------------------------------------
404 -- static pointers extension
405 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnStatic',
406
407 -- For details on above see note [Api annotations] in ApiAnnotation
408 | HsStatic (LHsExpr id)
409
410 ---------------------------------------
411 -- The following are commands, not expressions proper
412 -- They are only used in the parsing stage and are removed
413 -- immediately in parser.RdrHsSyn.checkCommand
414
415 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.Annlarrowtail',
416 -- 'ApiAnnotation.Annrarrowtail','ApiAnnotation.AnnLarrowtail',
417 -- 'ApiAnnotation.AnnRarrowtail'
418
419 -- For details on above see note [Api annotations] in ApiAnnotation
420 | HsArrApp -- Arrow tail, or arrow application (f -< arg)
421 (LHsExpr id) -- arrow expression, f
422 (LHsExpr id) -- input expression, arg
423 (PostTc id Type) -- type of the arrow expressions f,
424 -- of the form a t t', where arg :: t
425 HsArrAppType -- higher-order (-<<) or first-order (-<)
426 Bool -- True => right-to-left (f -< arg)
427 -- False => left-to-right (arg >- f)
428
429 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'(|'@,
430 -- 'ApiAnnotation.AnnClose' @'|)'@
431
432 -- For details on above see note [Api annotations] in ApiAnnotation
433 | HsArrForm -- Command formation, (| e cmd1 .. cmdn |)
434 (LHsExpr id) -- the operator
435 -- after type-checking, a type abstraction to be
436 -- applied to the type of the local environment tuple
437 (Maybe Fixity) -- fixity (filled in by the renamer), for forms that
438 -- were converted from OpApp's by the renamer
439 [LHsCmdTop id] -- argument commands
440
441 ---------------------------------------
442 -- Haskell program coverage (Hpc) Support
443
444 | HsTick
445 (Tickish id)
446 (LHsExpr id) -- sub-expression
447
448 | HsBinTick
449 Int -- module-local tick number for True
450 Int -- module-local tick number for False
451 (LHsExpr id) -- sub-expression
452
453 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
454 -- 'ApiAnnotation.AnnOpen' @'{-\# GENERATED'@,
455 -- 'ApiAnnotation.AnnVal','ApiAnnotation.AnnVal',
456 -- 'ApiAnnotation.AnnColon','ApiAnnotation.AnnVal',
457 -- 'ApiAnnotation.AnnMinus',
458 -- 'ApiAnnotation.AnnVal','ApiAnnotation.AnnColon',
459 -- 'ApiAnnotation.AnnVal',
460 -- 'ApiAnnotation.AnnClose' @'\#-}'@
461
462 -- For details on above see note [Api annotations] in ApiAnnotation
463 | HsTickPragma -- A pragma introduced tick
464 SourceText -- Note [Pragma source text] in BasicTypes
465 (FastString,(Int,Int),(Int,Int)) -- external span for this tick
466 (LHsExpr id)
467
468 ---------------------------------------
469 -- These constructors only appear temporarily in the parser.
470 -- The renamer translates them into the Right Thing.
471
472 | EWildPat -- wildcard
473
474 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnAt'
475
476 -- For details on above see note [Api annotations] in ApiAnnotation
477 | EAsPat (Located id) -- as pattern
478 (LHsExpr id)
479
480 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnRarrow'
481
482 -- For details on above see note [Api annotations] in ApiAnnotation
483 | EViewPat (LHsExpr id) -- view pattern
484 (LHsExpr id)
485
486 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnTilde'
487
488 -- For details on above see note [Api annotations] in ApiAnnotation
489 | ELazyPat (LHsExpr id) -- ~ pattern
490
491 | HsType (LHsType id) -- Explicit type argument; e.g f {| Int |} x y
492
493 ---------------------------------------
494 -- Finally, HsWrap appears only in typechecker output
495
496 | HsWrap HsWrapper -- TRANSLATION
497 (HsExpr id)
498 | HsUnboundVar RdrName
499 deriving (Typeable)
500 deriving instance (DataId id) => Data (HsExpr id)
501
502 -- | HsTupArg is used for tuple sections
503 -- (,a,) is represented by ExplicitTuple [Missing ty1, Present a, Missing ty3]
504 -- Which in turn stands for (\x:ty1 \y:ty2. (x,a,y))
505 type LHsTupArg id = Located (HsTupArg id)
506 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnComma'
507
508 -- For details on above see note [Api annotations] in ApiAnnotation
509 data HsTupArg id
510 = Present (LHsExpr id) -- ^ The argument
511 | Missing (PostTc id Type) -- ^ The argument is missing, but this is its type
512 deriving (Typeable)
513 deriving instance (DataId id) => Data (HsTupArg id)
514
515 tupArgPresent :: LHsTupArg id -> Bool
516 tupArgPresent (L _ (Present {})) = True
517 tupArgPresent (L _ (Missing {})) = False
518
519 {-
520 Note [Parens in HsSyn]
521 ~~~~~~~~~~~~~~~~~~~~~~
522 HsPar (and ParPat in patterns, HsParTy in types) is used as follows
523
524 * Generally HsPar is optional; the pretty printer adds parens where
525 necessary. Eg (HsApp f (HsApp g x)) is fine, and prints 'f (g x)'
526
527 * HsPars are pretty printed as '( .. )' regardless of whether
528 or not they are strictly necssary
529
530 * HsPars are respected when rearranging operator fixities.
531 So a * (b + c) means what it says (where the parens are an HsPar)
532
533 Note [Sections in HsSyn]
534 ~~~~~~~~~~~~~~~~~~~~~~~~
535 Sections should always appear wrapped in an HsPar, thus
536 HsPar (SectionR ...)
537 The parser parses sections in a wider variety of situations
538 (See Note [Parsing sections]), but the renamer checks for those
539 parens. This invariant makes pretty-printing easier; we don't need
540 a special case for adding the parens round sections.
541
542 Note [Rebindable if]
543 ~~~~~~~~~~~~~~~~~~~~
544 The rebindable syntax for 'if' is a bit special, because when
545 rebindable syntax is *off* we do not want to treat
546 (if c then t else e)
547 as if it was an application (ifThenElse c t e). Why not?
548 Because we allow an 'if' to return *unboxed* results, thus
549 if blah then 3# else 4#
550 whereas that would not be possible using a all to a polymorphic function
551 (because you can't call a polymorphic function at an unboxed type).
552
553 So we use Nothing to mean "use the old built-in typing rule".
554 -}
555
556 instance OutputableBndr id => Outputable (HsExpr id) where
557 ppr expr = pprExpr expr
558
559 -----------------------
560 -- pprExpr, pprLExpr, pprBinds call pprDeeper;
561 -- the underscore versions do not
562 pprLExpr :: OutputableBndr id => LHsExpr id -> SDoc
563 pprLExpr (L _ e) = pprExpr e
564
565 pprExpr :: OutputableBndr id => HsExpr id -> SDoc
566 pprExpr e | isAtomicHsExpr e || isQuietHsExpr e = ppr_expr e
567 | otherwise = pprDeeper (ppr_expr e)
568
569 isQuietHsExpr :: HsExpr id -> Bool
570 -- Parentheses do display something, but it gives little info and
571 -- if we go deeper when we go inside them then we get ugly things
572 -- like (...)
573 isQuietHsExpr (HsPar _) = True
574 -- applications don't display anything themselves
575 isQuietHsExpr (HsApp _ _) = True
576 isQuietHsExpr (OpApp _ _ _ _) = True
577 isQuietHsExpr _ = False
578
579 pprBinds :: (OutputableBndr idL, OutputableBndr idR)
580 => HsLocalBindsLR idL idR -> SDoc
581 pprBinds b = pprDeeper (ppr b)
582
583 -----------------------
584 ppr_lexpr :: OutputableBndr id => LHsExpr id -> SDoc
585 ppr_lexpr e = ppr_expr (unLoc e)
586
587 ppr_expr :: forall id. OutputableBndr id => HsExpr id -> SDoc
588 ppr_expr (HsVar v) = pprPrefixOcc v
589 ppr_expr (HsIPVar v) = ppr v
590 ppr_expr (HsLit lit) = ppr lit
591 ppr_expr (HsOverLit lit) = ppr lit
592 ppr_expr (HsPar e) = parens (ppr_lexpr e)
593
594 ppr_expr (HsCoreAnn _ s e)
595 = vcat [ptext (sLit "HsCoreAnn") <+> ftext s, ppr_lexpr e]
596
597 ppr_expr (HsApp e1 e2)
598 = let (fun, args) = collect_args e1 [e2] in
599 hang (ppr_lexpr fun) 2 (sep (map pprParendExpr args))
600 where
601 collect_args (L _ (HsApp fun arg)) args = collect_args fun (arg:args)
602 collect_args fun args = (fun, args)
603
604 ppr_expr (OpApp e1 op _ e2)
605 = case unLoc op of
606 HsVar v -> pp_infixly v
607 _ -> pp_prefixly
608 where
609 pp_e1 = pprDebugParendExpr e1 -- In debug mode, add parens
610 pp_e2 = pprDebugParendExpr e2 -- to make precedence clear
611
612 pp_prefixly
613 = hang (ppr op) 2 (sep [pp_e1, pp_e2])
614
615 pp_infixly v
616 = sep [pp_e1, sep [pprInfixOcc v, nest 2 pp_e2]]
617
618 ppr_expr (NegApp e _) = char '-' <+> pprDebugParendExpr e
619
620 ppr_expr (SectionL expr op)
621 = case unLoc op of
622 HsVar v -> pp_infixly v
623 _ -> pp_prefixly
624 where
625 pp_expr = pprDebugParendExpr expr
626
627 pp_prefixly = hang (hsep [text " \\ x_ ->", ppr op])
628 4 (hsep [pp_expr, ptext (sLit "x_ )")])
629 pp_infixly v = (sep [pp_expr, pprInfixOcc v])
630
631 ppr_expr (SectionR op expr)
632 = case unLoc op of
633 HsVar v -> pp_infixly v
634 _ -> pp_prefixly
635 where
636 pp_expr = pprDebugParendExpr expr
637
638 pp_prefixly = hang (hsep [text "( \\ x_ ->", ppr op, ptext (sLit "x_")])
639 4 (pp_expr <> rparen)
640 pp_infixly v = sep [pprInfixOcc v, pp_expr]
641
642 ppr_expr (ExplicitTuple exprs boxity)
643 = tupleParens (boxityNormalTupleSort boxity)
644 (fcat (ppr_tup_args $ map unLoc exprs))
645 where
646 ppr_tup_args [] = []
647 ppr_tup_args (Present e : es) = (ppr_lexpr e <> punc es) : ppr_tup_args es
648 ppr_tup_args (Missing _ : es) = punc es : ppr_tup_args es
649
650 punc (Present {} : _) = comma <> space
651 punc (Missing {} : _) = comma
652 punc [] = empty
653
654 --avoid using PatternSignatures for stage1 code portability
655 ppr_expr (HsLam matches)
656 = pprMatches (LambdaExpr :: HsMatchContext id) matches
657
658 ppr_expr (HsLamCase _ matches)
659 = sep [ sep [ptext (sLit "\\case {")],
660 nest 2 (pprMatches (CaseAlt :: HsMatchContext id) matches <+> char '}') ]
661
662 ppr_expr (HsCase expr matches)
663 = sep [ sep [ptext (sLit "case"), nest 4 (ppr expr), ptext (sLit "of {")],
664 nest 2 (pprMatches (CaseAlt :: HsMatchContext id) matches <+> char '}') ]
665
666 ppr_expr (HsIf _ e1 e2 e3)
667 = sep [hsep [ptext (sLit "if"), nest 2 (ppr e1), ptext (sLit "then")],
668 nest 4 (ppr e2),
669 ptext (sLit "else"),
670 nest 4 (ppr e3)]
671
672 ppr_expr (HsMultiIf _ alts)
673 = sep $ ptext (sLit "if") : map ppr_alt alts
674 where ppr_alt (L _ (GRHS guards expr)) =
675 sep [ char '|' <+> interpp'SP guards
676 , ptext (sLit "->") <+> pprDeeper (ppr expr) ]
677
678 -- special case: let ... in let ...
679 ppr_expr (HsLet binds expr@(L _ (HsLet _ _)))
680 = sep [hang (ptext (sLit "let")) 2 (hsep [pprBinds binds, ptext (sLit "in")]),
681 ppr_lexpr expr]
682
683 ppr_expr (HsLet binds expr)
684 = sep [hang (ptext (sLit "let")) 2 (pprBinds binds),
685 hang (ptext (sLit "in")) 2 (ppr expr)]
686
687 ppr_expr (HsDo do_or_list_comp stmts _) = pprDo do_or_list_comp stmts
688
689 ppr_expr (ExplicitList _ _ exprs)
690 = brackets (pprDeeperList fsep (punctuate comma (map ppr_lexpr exprs)))
691
692 ppr_expr (ExplicitPArr _ exprs)
693 = paBrackets (pprDeeperList fsep (punctuate comma (map ppr_lexpr exprs)))
694
695 ppr_expr (RecordCon con_id _ rbinds)
696 = hang (ppr con_id) 2 (ppr rbinds)
697
698 ppr_expr (RecordUpd aexp rbinds _ _ _)
699 = hang (pprParendExpr aexp) 2 (ppr rbinds)
700
701 ppr_expr (ExprWithTySig expr sig _)
702 = hang (nest 2 (ppr_lexpr expr) <+> dcolon)
703 4 (ppr sig)
704 ppr_expr (ExprWithTySigOut expr sig)
705 = hang (nest 2 (ppr_lexpr expr) <+> dcolon)
706 4 (ppr sig)
707
708 ppr_expr (ArithSeq _ _ info) = brackets (ppr info)
709 ppr_expr (PArrSeq _ info) = paBrackets (ppr info)
710
711 ppr_expr EWildPat = char '_'
712 ppr_expr (ELazyPat e) = char '~' <> pprParendExpr e
713 ppr_expr (EAsPat v e) = ppr v <> char '@' <> pprParendExpr e
714 ppr_expr (EViewPat p e) = ppr p <+> ptext (sLit "->") <+> ppr e
715
716 ppr_expr (HsSCC _ lbl expr)
717 = sep [ ptext (sLit "{-# SCC") <+> doubleQuotes (ftext lbl) <+> ptext (sLit "#-}"),
718 pprParendExpr expr ]
719
720 ppr_expr (HsWrap co_fn e) = pprHsWrapper (pprExpr e) co_fn
721 ppr_expr (HsType id) = ppr id
722
723 ppr_expr (HsSpliceE t s) = pprSplice t s
724 ppr_expr (HsBracket b) = pprHsBracket b
725 ppr_expr (HsRnBracketOut e []) = ppr e
726 ppr_expr (HsRnBracketOut e ps) = ppr e $$ ptext (sLit "pending(rn)") <+> ppr ps
727 ppr_expr (HsTcBracketOut e []) = ppr e
728 ppr_expr (HsTcBracketOut e ps) = ppr e $$ ptext (sLit "pending(tc)") <+> ppr ps
729 ppr_expr (HsQuasiQuoteE qq) = ppr qq
730
731 ppr_expr (HsProc pat (L _ (HsCmdTop cmd _ _ _)))
732 = hsep [ptext (sLit "proc"), ppr pat, ptext (sLit "->"), ppr cmd]
733
734 ppr_expr (HsStatic e)
735 = hsep [ptext (sLit "static"), pprParendExpr e]
736
737 ppr_expr (HsTick tickish exp)
738 = pprTicks (ppr exp) $
739 ppr tickish <+> ppr_lexpr exp
740 ppr_expr (HsBinTick tickIdTrue tickIdFalse exp)
741 = pprTicks (ppr exp) $
742 hcat [ptext (sLit "bintick<"),
743 ppr tickIdTrue,
744 ptext (sLit ","),
745 ppr tickIdFalse,
746 ptext (sLit ">("),
747 ppr exp,ptext (sLit ")")]
748 ppr_expr (HsTickPragma _ externalSrcLoc exp)
749 = pprTicks (ppr exp) $
750 hcat [ptext (sLit "tickpragma<"),
751 ppr externalSrcLoc,
752 ptext (sLit ">("),
753 ppr exp,
754 ptext (sLit ")")]
755
756 ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp True)
757 = hsep [ppr_lexpr arrow, larrowt, ppr_lexpr arg]
758 ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp False)
759 = hsep [ppr_lexpr arg, arrowt, ppr_lexpr arrow]
760 ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp True)
761 = hsep [ppr_lexpr arrow, larrowtt, ppr_lexpr arg]
762 ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp False)
763 = hsep [ppr_lexpr arg, arrowtt, ppr_lexpr arrow]
764
765 ppr_expr (HsArrForm (L _ (HsVar v)) (Just _) [arg1, arg2])
766 = sep [pprCmdArg (unLoc arg1), hsep [pprInfixOcc v, pprCmdArg (unLoc arg2)]]
767 ppr_expr (HsArrForm op _ args)
768 = hang (ptext (sLit "(|") <+> ppr_lexpr op)
769 4 (sep (map (pprCmdArg.unLoc) args) <+> ptext (sLit "|)"))
770 ppr_expr (HsUnboundVar nm)
771 = ppr nm
772
773 {-
774 HsSyn records exactly where the user put parens, with HsPar.
775 So generally speaking we print without adding any parens.
776 However, some code is internally generated, and in some places
777 parens are absolutely required; so for these places we use
778 pprParendExpr (but don't print double parens of course).
779
780 For operator applications we don't add parens, because the oprerator
781 fixities should do the job, except in debug mode (-dppr-debug) so we
782 can see the structure of the parse tree.
783 -}
784
785 pprDebugParendExpr :: OutputableBndr id => LHsExpr id -> SDoc
786 pprDebugParendExpr expr
787 = getPprStyle (\sty ->
788 if debugStyle sty then pprParendExpr expr
789 else pprLExpr expr)
790
791 pprParendExpr :: OutputableBndr id => LHsExpr id -> SDoc
792 pprParendExpr expr
793 | hsExprNeedsParens (unLoc expr) = parens (pprLExpr expr)
794 | otherwise = pprLExpr expr
795 -- Using pprLExpr makes sure that we go 'deeper'
796 -- I think that is usually (always?) right
797
798 hsExprNeedsParens :: HsExpr id -> Bool
799 -- True of expressions for which '(e)' and 'e'
800 -- mean the same thing
801 hsExprNeedsParens (ArithSeq {}) = False
802 hsExprNeedsParens (PArrSeq {}) = False
803 hsExprNeedsParens (HsLit {}) = False
804 hsExprNeedsParens (HsOverLit {}) = False
805 hsExprNeedsParens (HsVar {}) = False
806 hsExprNeedsParens (HsUnboundVar {}) = False
807 hsExprNeedsParens (HsIPVar {}) = False
808 hsExprNeedsParens (ExplicitTuple {}) = False
809 hsExprNeedsParens (ExplicitList {}) = False
810 hsExprNeedsParens (ExplicitPArr {}) = False
811 hsExprNeedsParens (HsPar {}) = False
812 hsExprNeedsParens (HsBracket {}) = False
813 hsExprNeedsParens (HsRnBracketOut {}) = False
814 hsExprNeedsParens (HsTcBracketOut {}) = False
815 hsExprNeedsParens (HsDo sc _ _)
816 | isListCompExpr sc = False
817 hsExprNeedsParens _ = True
818
819
820 isAtomicHsExpr :: HsExpr id -> Bool
821 -- True of a single token
822 isAtomicHsExpr (HsVar {}) = True
823 isAtomicHsExpr (HsLit {}) = True
824 isAtomicHsExpr (HsOverLit {}) = True
825 isAtomicHsExpr (HsIPVar {}) = True
826 isAtomicHsExpr (HsUnboundVar {}) = True
827 isAtomicHsExpr (HsWrap _ e) = isAtomicHsExpr e
828 isAtomicHsExpr (HsPar e) = isAtomicHsExpr (unLoc e)
829 isAtomicHsExpr _ = False
830
831 {-
832 ************************************************************************
833 * *
834 \subsection{Commands (in arrow abstractions)}
835 * *
836 ************************************************************************
837
838 We re-use HsExpr to represent these.
839 -}
840
841 type LHsCmd id = Located (HsCmd id)
842
843 data HsCmd id
844 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.Annlarrowtail',
845 -- 'ApiAnnotation.Annrarrowtail','ApiAnnotation.AnnLarrowtail',
846 -- 'ApiAnnotation.AnnRarrowtail'
847
848 -- For details on above see note [Api annotations] in ApiAnnotation
849 = HsCmdArrApp -- Arrow tail, or arrow application (f -< arg)
850 (LHsExpr id) -- arrow expression, f
851 (LHsExpr id) -- input expression, arg
852 (PostTc id Type) -- type of the arrow expressions f,
853 -- of the form a t t', where arg :: t
854 HsArrAppType -- higher-order (-<<) or first-order (-<)
855 Bool -- True => right-to-left (f -< arg)
856 -- False => left-to-right (arg >- f)
857
858 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'(|'@,
859 -- 'ApiAnnotation.AnnClose' @'|)'@
860
861 -- For details on above see note [Api annotations] in ApiAnnotation
862 | HsCmdArrForm -- Command formation, (| e cmd1 .. cmdn |)
863 (LHsExpr id) -- the operator
864 -- after type-checking, a type abstraction to be
865 -- applied to the type of the local environment tuple
866 (Maybe Fixity) -- fixity (filled in by the renamer), for forms that
867 -- were converted from OpApp's by the renamer
868 [LHsCmdTop id] -- argument commands
869
870 | HsCmdApp (LHsCmd id)
871 (LHsExpr id)
872
873 | HsCmdLam (MatchGroup id (LHsCmd id)) -- kappa
874 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLam',
875 -- 'ApiAnnotation.AnnRarrow',
876
877 -- For details on above see note [Api annotations] in ApiAnnotation
878
879 | HsCmdPar (LHsCmd id) -- parenthesised command
880 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@,
881 -- 'ApiAnnotation.AnnClose' @')'@
882
883 -- For details on above see note [Api annotations] in ApiAnnotation
884
885 | HsCmdCase (LHsExpr id)
886 (MatchGroup id (LHsCmd id)) -- bodies are HsCmd's
887 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnCase',
888 -- 'ApiAnnotation.AnnOf','ApiAnnotation.AnnOpen' @'{'@,
889 -- 'ApiAnnotation.AnnClose' @'}'@
890
891 -- For details on above see note [Api annotations] in ApiAnnotation
892
893 | HsCmdIf (Maybe (SyntaxExpr id)) -- cond function
894 (LHsExpr id) -- predicate
895 (LHsCmd id) -- then part
896 (LHsCmd id) -- else part
897 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnIf',
898 -- 'ApiAnnotation.AnnSemi',
899 -- 'ApiAnnotation.AnnThen','ApiAnnotation.AnnSemi',
900 -- 'ApiAnnotation.AnnElse',
901
902 -- For details on above see note [Api annotations] in ApiAnnotation
903
904 | HsCmdLet (HsLocalBinds id) -- let(rec)
905 (LHsCmd id)
906 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLet',
907 -- 'ApiAnnotation.AnnOpen' @'{'@,
908 -- 'ApiAnnotation.AnnClose' @'}'@,'ApiAnnotation.AnnIn'
909
910 -- For details on above see note [Api annotations] in ApiAnnotation
911
912 | HsCmdDo [CmdLStmt id]
913 (PostTc id Type) -- Type of the whole expression
914 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDo',
915 -- 'ApiAnnotation.AnnOpen', 'ApiAnnotation.AnnSemi',
916 -- 'ApiAnnotation.AnnVbar',
917 -- 'ApiAnnotation.AnnClose'
918
919 -- For details on above see note [Api annotations] in ApiAnnotation
920
921 | HsCmdCast TcCoercion -- A simpler version of HsWrap in HsExpr
922 (HsCmd id) -- If cmd :: arg1 --> res
923 -- co :: arg1 ~ arg2
924 -- Then (HsCmdCast co cmd) :: arg2 --> res
925 deriving (Typeable)
926 deriving instance (DataId id) => Data (HsCmd id)
927
928 data HsArrAppType = HsHigherOrderApp | HsFirstOrderApp
929 deriving (Data, Typeable)
930
931
932 {- | Top-level command, introducing a new arrow.
933 This may occur inside a proc (where the stack is empty) or as an
934 argument of a command-forming operator.
935 -}
936
937 type LHsCmdTop id = Located (HsCmdTop id)
938
939 data HsCmdTop id
940 = HsCmdTop (LHsCmd id)
941 (PostTc id Type) -- Nested tuple of inputs on the command's stack
942 (PostTc id Type) -- return type of the command
943 (CmdSyntaxTable id) -- See Note [CmdSyntaxTable]
944 deriving (Typeable)
945 deriving instance (DataId id) => Data (HsCmdTop id)
946
947 instance OutputableBndr id => Outputable (HsCmd id) where
948 ppr cmd = pprCmd cmd
949
950 -----------------------
951 -- pprCmd and pprLCmd call pprDeeper;
952 -- the underscore versions do not
953 pprLCmd :: OutputableBndr id => LHsCmd id -> SDoc
954 pprLCmd (L _ c) = pprCmd c
955
956 pprCmd :: OutputableBndr id => HsCmd id -> SDoc
957 pprCmd c | isQuietHsCmd c = ppr_cmd c
958 | otherwise = pprDeeper (ppr_cmd c)
959
960 isQuietHsCmd :: HsCmd id -> Bool
961 -- Parentheses do display something, but it gives little info and
962 -- if we go deeper when we go inside them then we get ugly things
963 -- like (...)
964 isQuietHsCmd (HsCmdPar _) = True
965 -- applications don't display anything themselves
966 isQuietHsCmd (HsCmdApp _ _) = True
967 isQuietHsCmd _ = False
968
969 -----------------------
970 ppr_lcmd :: OutputableBndr id => LHsCmd id -> SDoc
971 ppr_lcmd c = ppr_cmd (unLoc c)
972
973 ppr_cmd :: forall id. OutputableBndr id => HsCmd id -> SDoc
974 ppr_cmd (HsCmdPar c) = parens (ppr_lcmd c)
975
976 ppr_cmd (HsCmdApp c e)
977 = let (fun, args) = collect_args c [e] in
978 hang (ppr_lcmd fun) 2 (sep (map pprParendExpr args))
979 where
980 collect_args (L _ (HsCmdApp fun arg)) args = collect_args fun (arg:args)
981 collect_args fun args = (fun, args)
982
983 --avoid using PatternSignatures for stage1 code portability
984 ppr_cmd (HsCmdLam matches)
985 = pprMatches (LambdaExpr :: HsMatchContext id) matches
986
987 ppr_cmd (HsCmdCase expr matches)
988 = sep [ sep [ptext (sLit "case"), nest 4 (ppr expr), ptext (sLit "of {")],
989 nest 2 (pprMatches (CaseAlt :: HsMatchContext id) matches <+> char '}') ]
990
991 ppr_cmd (HsCmdIf _ e ct ce)
992 = sep [hsep [ptext (sLit "if"), nest 2 (ppr e), ptext (sLit "then")],
993 nest 4 (ppr ct),
994 ptext (sLit "else"),
995 nest 4 (ppr ce)]
996
997 -- special case: let ... in let ...
998 ppr_cmd (HsCmdLet binds cmd@(L _ (HsCmdLet _ _)))
999 = sep [hang (ptext (sLit "let")) 2 (hsep [pprBinds binds, ptext (sLit "in")]),
1000 ppr_lcmd cmd]
1001
1002 ppr_cmd (HsCmdLet binds cmd)
1003 = sep [hang (ptext (sLit "let")) 2 (pprBinds binds),
1004 hang (ptext (sLit "in")) 2 (ppr cmd)]
1005
1006 ppr_cmd (HsCmdDo stmts _) = pprDo ArrowExpr stmts
1007 ppr_cmd (HsCmdCast co cmd) = sep [ ppr_cmd cmd
1008 , ptext (sLit "|>") <+> ppr co ]
1009
1010 ppr_cmd (HsCmdArrApp arrow arg _ HsFirstOrderApp True)
1011 = hsep [ppr_lexpr arrow, larrowt, ppr_lexpr arg]
1012 ppr_cmd (HsCmdArrApp arrow arg _ HsFirstOrderApp False)
1013 = hsep [ppr_lexpr arg, arrowt, ppr_lexpr arrow]
1014 ppr_cmd (HsCmdArrApp arrow arg _ HsHigherOrderApp True)
1015 = hsep [ppr_lexpr arrow, larrowtt, ppr_lexpr arg]
1016 ppr_cmd (HsCmdArrApp arrow arg _ HsHigherOrderApp False)
1017 = hsep [ppr_lexpr arg, arrowtt, ppr_lexpr arrow]
1018
1019 ppr_cmd (HsCmdArrForm (L _ (HsVar v)) (Just _) [arg1, arg2])
1020 = sep [pprCmdArg (unLoc arg1), hsep [pprInfixOcc v, pprCmdArg (unLoc arg2)]]
1021 ppr_cmd (HsCmdArrForm op _ args)
1022 = hang (ptext (sLit "(|") <> ppr_lexpr op)
1023 4 (sep (map (pprCmdArg.unLoc) args) <> ptext (sLit "|)"))
1024
1025 pprCmdArg :: OutputableBndr id => HsCmdTop id -> SDoc
1026 pprCmdArg (HsCmdTop cmd@(L _ (HsCmdArrForm _ Nothing [])) _ _ _)
1027 = ppr_lcmd cmd
1028 pprCmdArg (HsCmdTop cmd _ _ _)
1029 = parens (ppr_lcmd cmd)
1030
1031 instance OutputableBndr id => Outputable (HsCmdTop id) where
1032 ppr = pprCmdArg
1033
1034 {-
1035 ************************************************************************
1036 * *
1037 \subsection{Record binds}
1038 * *
1039 ************************************************************************
1040 -}
1041
1042 type HsRecordBinds id = HsRecFields id (LHsExpr id)
1043
1044 {-
1045 ************************************************************************
1046 * *
1047 \subsection{@Match@, @GRHSs@, and @GRHS@ datatypes}
1048 * *
1049 ************************************************************************
1050
1051 @Match@es are sets of pattern bindings and right hand sides for
1052 functions, patterns or case branches. For example, if a function @g@
1053 is defined as:
1054 \begin{verbatim}
1055 g (x,y) = y
1056 g ((x:ys),y) = y+1,
1057 \end{verbatim}
1058 then \tr{g} has two @Match@es: @(x,y) = y@ and @((x:ys),y) = y+1@.
1059
1060 It is always the case that each element of an @[Match]@ list has the
1061 same number of @pats@s inside it. This corresponds to saying that
1062 a function defined by pattern matching must have the same number of
1063 patterns in each equation.
1064 -}
1065
1066 data MatchGroup id body
1067 = MG { mg_alts :: [LMatch id body] -- The alternatives
1068 , mg_arg_tys :: [PostTc id Type] -- Types of the arguments, t1..tn
1069 , mg_res_ty :: PostTc id Type -- Type of the result, tr
1070 , mg_origin :: Origin }
1071 -- The type is the type of the entire group
1072 -- t1 -> ... -> tn -> tr
1073 -- where there are n patterns
1074 deriving (Typeable)
1075 deriving instance (Data body,DataId id) => Data (MatchGroup id body)
1076
1077 type LMatch id body = Located (Match id body)
1078 -- ^ May have 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnSemi' when in a
1079 -- list
1080
1081 -- For details on above see note [Api annotations] in ApiAnnotation
1082 data Match id body
1083 = Match {
1084 m_fun_id_infix :: (Maybe (Located id,Bool)),
1085 -- fun_id and fun_infix for functions with multiple equations
1086 -- only present for a RdrName. See note [fun_id in Match]
1087 m_pats :: [LPat id], -- The patterns
1088 m_type :: (Maybe (LHsType id)),
1089 -- A type signature for the result of the match
1090 -- Nothing after typechecking
1091 m_grhss :: (GRHSs id body)
1092 } deriving (Typeable)
1093 deriving instance (Data body,DataId id) => Data (Match id body)
1094
1095 {-
1096 Note [fun_id in Match]
1097 ~~~~~~~~~~~~~~~~~~~~~~
1098
1099 The parser initially creates a FunBind with a single Match in it for
1100 every function definition it sees.
1101
1102 These are then grouped together by getMonoBind into a single FunBind,
1103 where all the Matches are combined.
1104
1105 In the process, all the original FunBind fun_id's bar one are
1106 discarded, including the locations.
1107
1108 This causes a problem for source to source conversions via API
1109 Annotations, so the original fun_ids and infix flags are preserved in
1110 the Match, when it originates from a FunBind.
1111
1112 Example infix function definition requiring individual API Annotations
1113
1114 (&&& ) [] [] = []
1115 xs &&& [] = xs
1116 ( &&& ) [] ys = ys
1117
1118
1119 -}
1120
1121 isEmptyMatchGroup :: MatchGroup id body -> Bool
1122 isEmptyMatchGroup (MG { mg_alts = ms }) = null ms
1123
1124 matchGroupArity :: MatchGroup id body -> Arity
1125 -- Precondition: MatchGroup is non-empty
1126 -- This is called before type checking, when mg_arg_tys is not set
1127 matchGroupArity (MG { mg_alts = alts })
1128 | (alt1:_) <- alts = length (hsLMatchPats alt1)
1129 | otherwise = panic "matchGroupArity"
1130
1131 hsLMatchPats :: LMatch id body -> [LPat id]
1132 hsLMatchPats (L _ (Match _ pats _ _)) = pats
1133
1134 -- | GRHSs are used both for pattern bindings and for Matches
1135 --
1136 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnVbar',
1137 -- 'ApiAnnotation.AnnEqual','ApiAnnotation.AnnWhere',
1138 -- 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose'
1139 -- 'ApiAnnotation.AnnRarrow','ApiAnnotation.AnnSemi'
1140
1141 -- For details on above see note [Api annotations] in ApiAnnotation
1142 data GRHSs id body
1143 = GRHSs {
1144 grhssGRHSs :: [LGRHS id body], -- ^ Guarded RHSs
1145 grhssLocalBinds :: (HsLocalBinds id) -- ^ The where clause
1146 } deriving (Typeable)
1147 deriving instance (Data body,DataId id) => Data (GRHSs id body)
1148
1149 type LGRHS id body = Located (GRHS id body)
1150
1151 -- | Guarded Right Hand Side.
1152 data GRHS id body = GRHS [GuardLStmt id] -- Guards
1153 body -- Right hand side
1154 deriving (Typeable)
1155 deriving instance (Data body,DataId id) => Data (GRHS id body)
1156
1157 -- We know the list must have at least one @Match@ in it.
1158
1159 pprMatches :: (OutputableBndr idL, OutputableBndr idR, Outputable body)
1160 => HsMatchContext idL -> MatchGroup idR body -> SDoc
1161 pprMatches ctxt (MG { mg_alts = matches })
1162 = vcat (map (pprMatch ctxt) (map unLoc matches))
1163 -- Don't print the type; it's only a place-holder before typechecking
1164
1165 -- Exported to HsBinds, which can't see the defn of HsMatchContext
1166 pprFunBind :: (OutputableBndr idL, OutputableBndr idR, Outputable body)
1167 => idL -> Bool -> MatchGroup idR body -> SDoc
1168 pprFunBind fun inf matches = pprMatches (FunRhs fun inf) matches
1169
1170 -- Exported to HsBinds, which can't see the defn of HsMatchContext
1171 pprPatBind :: forall bndr id body. (OutputableBndr bndr, OutputableBndr id, Outputable body)
1172 => LPat bndr -> GRHSs id body -> SDoc
1173 pprPatBind pat (grhss)
1174 = sep [ppr pat, nest 2 (pprGRHSs (PatBindRhs :: HsMatchContext id) grhss)]
1175
1176 pprMatch :: (OutputableBndr idL, OutputableBndr idR, Outputable body)
1177 => HsMatchContext idL -> Match idR body -> SDoc
1178 pprMatch ctxt (Match _ pats maybe_ty grhss)
1179 = sep [ sep (herald : map (nest 2 . pprParendLPat) other_pats)
1180 , nest 2 ppr_maybe_ty
1181 , nest 2 (pprGRHSs ctxt grhss) ]
1182 where
1183 (herald, other_pats)
1184 = case ctxt of
1185 FunRhs fun is_infix
1186 | not is_infix -> (pprPrefixOcc fun, pats)
1187 -- f x y z = e
1188 -- Not pprBndr; the AbsBinds will
1189 -- have printed the signature
1190
1191 | null pats2 -> (pp_infix, [])
1192 -- x &&& y = e
1193
1194 | otherwise -> (parens pp_infix, pats2)
1195 -- (x &&& y) z = e
1196 where
1197 pp_infix = pprParendLPat pat1 <+> pprInfixOcc fun <+> pprParendLPat pat2
1198
1199 LambdaExpr -> (char '\\', pats)
1200
1201 _ -> ASSERT( null pats1 )
1202 (ppr pat1, []) -- No parens around the single pat
1203
1204 (pat1:pats1) = pats
1205 (pat2:pats2) = pats1
1206 ppr_maybe_ty = case maybe_ty of
1207 Just ty -> dcolon <+> ppr ty
1208 Nothing -> empty
1209
1210
1211 pprGRHSs :: (OutputableBndr idR, Outputable body)
1212 => HsMatchContext idL -> GRHSs idR body -> SDoc
1213 pprGRHSs ctxt (GRHSs grhss binds)
1214 = vcat (map (pprGRHS ctxt . unLoc) grhss)
1215 $$ ppUnless (isEmptyLocalBinds binds)
1216 (text "where" $$ nest 4 (pprBinds binds))
1217
1218 pprGRHS :: (OutputableBndr idR, Outputable body)
1219 => HsMatchContext idL -> GRHS idR body -> SDoc
1220 pprGRHS ctxt (GRHS [] body)
1221 = pp_rhs ctxt body
1222
1223 pprGRHS ctxt (GRHS guards body)
1224 = sep [char '|' <+> interpp'SP guards, pp_rhs ctxt body]
1225
1226 pp_rhs :: Outputable body => HsMatchContext idL -> body -> SDoc
1227 pp_rhs ctxt rhs = matchSeparator ctxt <+> pprDeeper (ppr rhs)
1228
1229 {-
1230 ************************************************************************
1231 * *
1232 \subsection{Do stmts and list comprehensions}
1233 * *
1234 ************************************************************************
1235 -}
1236
1237 type LStmt id body = Located (StmtLR id id body)
1238 type LStmtLR idL idR body = Located (StmtLR idL idR body)
1239
1240 type Stmt id body = StmtLR id id body
1241
1242 type CmdLStmt id = LStmt id (LHsCmd id)
1243 type CmdStmt id = Stmt id (LHsCmd id)
1244 type ExprLStmt id = LStmt id (LHsExpr id)
1245 type ExprStmt id = Stmt id (LHsExpr id)
1246
1247 type GuardLStmt id = LStmt id (LHsExpr id)
1248 type GuardStmt id = Stmt id (LHsExpr id)
1249 type GhciLStmt id = LStmt id (LHsExpr id)
1250 type GhciStmt id = Stmt id (LHsExpr id)
1251
1252 -- The SyntaxExprs in here are used *only* for do-notation and monad
1253 -- comprehensions, which have rebindable syntax. Otherwise they are unused.
1254 -- | API Annotations when in qualifier lists or guards
1255 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnVbar',
1256 -- 'ApiAnnotation.AnnComma','ApiAnnotation.AnnThen',
1257 -- 'ApiAnnotation.AnnBy','ApiAnnotation.AnnBy',
1258 -- 'ApiAnnotation.AnnGroup','ApiAnnotation.AnnUsing'
1259
1260 -- For details on above see note [Api annotations] in ApiAnnotation
1261 data StmtLR idL idR body -- body should always be (LHs**** idR)
1262 = LastStmt -- Always the last Stmt in ListComp, MonadComp, PArrComp,
1263 -- and (after the renamer) DoExpr, MDoExpr
1264 -- Not used for GhciStmtCtxt, PatGuard, which scope over other stuff
1265 body
1266 (SyntaxExpr idR) -- The return operator, used only for MonadComp
1267 -- For ListComp, PArrComp, we use the baked-in 'return'
1268 -- For DoExpr, MDoExpr, we don't appply a 'return' at all
1269 -- See Note [Monad Comprehensions]
1270 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLarrow'
1271
1272 -- For details on above see note [Api annotations] in ApiAnnotation
1273 | BindStmt (LPat idL)
1274 body
1275 (SyntaxExpr idR) -- The (>>=) operator; see Note [The type of bind]
1276 (SyntaxExpr idR) -- The fail operator
1277 -- The fail operator is noSyntaxExpr
1278 -- if the pattern match can't fail
1279
1280 | BodyStmt body -- See Note [BodyStmt]
1281 (SyntaxExpr idR) -- The (>>) operator
1282 (SyntaxExpr idR) -- The `guard` operator; used only in MonadComp
1283 -- See notes [Monad Comprehensions]
1284 (PostTc idR Type) -- Element type of the RHS (used for arrows)
1285
1286 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLet'
1287 -- 'ApiAnnotation.AnnOpen' @'{'@,'ApiAnnotation.AnnClose' @'}'@,
1288
1289 -- For details on above see note [Api annotations] in ApiAnnotation
1290 | LetStmt (HsLocalBindsLR idL idR)
1291
1292 -- ParStmts only occur in a list/monad comprehension
1293 | ParStmt [ParStmtBlock idL idR]
1294 (SyntaxExpr idR) -- Polymorphic `mzip` for monad comprehensions
1295 (SyntaxExpr idR) -- The `>>=` operator
1296 -- See notes [Monad Comprehensions]
1297 -- After renaming, the ids are the binders
1298 -- bound by the stmts and used after themp
1299
1300 | TransStmt {
1301 trS_form :: TransForm,
1302 trS_stmts :: [ExprLStmt idL], -- Stmts to the *left* of the 'group'
1303 -- which generates the tuples to be grouped
1304
1305 trS_bndrs :: [(idR, idR)], -- See Note [TransStmt binder map]
1306
1307 trS_using :: LHsExpr idR,
1308 trS_by :: Maybe (LHsExpr idR), -- "by e" (optional)
1309 -- Invariant: if trS_form = GroupBy, then grp_by = Just e
1310
1311 trS_ret :: SyntaxExpr idR, -- The monomorphic 'return' function for
1312 -- the inner monad comprehensions
1313 trS_bind :: SyntaxExpr idR, -- The '(>>=)' operator
1314 trS_fmap :: SyntaxExpr idR -- The polymorphic 'fmap' function for desugaring
1315 -- Only for 'group' forms
1316 } -- See Note [Monad Comprehensions]
1317
1318 -- Recursive statement (see Note [How RecStmt works] below)
1319 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnRec'
1320
1321 -- For details on above see note [Api annotations] in ApiAnnotation
1322 | RecStmt
1323 { recS_stmts :: [LStmtLR idL idR body]
1324
1325 -- The next two fields are only valid after renaming
1326 , recS_later_ids :: [idR] -- The ids are a subset of the variables bound by the
1327 -- stmts that are used in stmts that follow the RecStmt
1328
1329 , recS_rec_ids :: [idR] -- Ditto, but these variables are the "recursive" ones,
1330 -- that are used before they are bound in the stmts of
1331 -- the RecStmt.
1332 -- An Id can be in both groups
1333 -- Both sets of Ids are (now) treated monomorphically
1334 -- See Note [How RecStmt works] for why they are separate
1335
1336 -- Rebindable syntax
1337 , recS_bind_fn :: SyntaxExpr idR -- The bind function
1338 , recS_ret_fn :: SyntaxExpr idR -- The return function
1339 , recS_mfix_fn :: SyntaxExpr idR -- The mfix function
1340
1341 -- These fields are only valid after typechecking
1342 , recS_later_rets :: [PostTcExpr] -- (only used in the arrow version)
1343 , recS_rec_rets :: [PostTcExpr] -- These expressions correspond 1-to-1
1344 -- with recS_later_ids and recS_rec_ids,
1345 -- and are the expressions that should be
1346 -- returned by the recursion.
1347 -- They may not quite be the Ids themselves,
1348 -- because the Id may be *polymorphic*, but
1349 -- the returned thing has to be *monomorphic*,
1350 -- so they may be type applications
1351
1352 , recS_ret_ty :: PostTc idR Type -- The type of
1353 -- do { stmts; return (a,b,c) }
1354 -- With rebindable syntax the type might not
1355 -- be quite as simple as (m (tya, tyb, tyc)).
1356 }
1357 deriving (Typeable)
1358 deriving instance (Data body, DataId idL, DataId idR)
1359 => Data (StmtLR idL idR body)
1360
1361 data TransForm -- The 'f' below is the 'using' function, 'e' is the by function
1362 = ThenForm -- then f or then f by e (depending on trS_by)
1363 | GroupForm -- then group using f or then group by e using f (depending on trS_by)
1364 deriving (Data, Typeable)
1365
1366 data ParStmtBlock idL idR
1367 = ParStmtBlock
1368 [ExprLStmt idL]
1369 [idR] -- The variables to be returned
1370 (SyntaxExpr idR) -- The return operator
1371 deriving( Typeable )
1372 deriving instance (DataId idL, DataId idR) => Data (ParStmtBlock idL idR)
1373
1374 {-
1375 Note [The type of bind in Stmts]
1376 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1377 Some Stmts, notably BindStmt, keep the (>>=) bind operator.
1378 We do NOT assume that it has type
1379 (>>=) :: m a -> (a -> m b) -> m b
1380 In some cases (see Trac #303, #1537) it might have a more
1381 exotic type, such as
1382 (>>=) :: m i j a -> (a -> m j k b) -> m i k b
1383 So we must be careful not to make assumptions about the type.
1384 In particular, the monad may not be uniform throughout.
1385
1386 Note [TransStmt binder map]
1387 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1388 The [(idR,idR)] in a TransStmt behaves as follows:
1389
1390 * Before renaming: []
1391
1392 * After renaming:
1393 [ (x27,x27), ..., (z35,z35) ]
1394 These are the variables
1395 bound by the stmts to the left of the 'group'
1396 and used either in the 'by' clause,
1397 or in the stmts following the 'group'
1398 Each item is a pair of identical variables.
1399
1400 * After typechecking:
1401 [ (x27:Int, x27:[Int]), ..., (z35:Bool, z35:[Bool]) ]
1402 Each pair has the same unique, but different *types*.
1403
1404 Note [BodyStmt]
1405 ~~~~~~~~~~~~~~~
1406 BodyStmts are a bit tricky, because what they mean
1407 depends on the context. Consider the following contexts:
1408
1409 A do expression of type (m res_ty)
1410 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1411 * BodyStmt E any_ty: do { ....; E; ... }
1412 E :: m any_ty
1413 Translation: E >> ...
1414
1415 A list comprehensions of type [elt_ty]
1416 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1417 * BodyStmt E Bool: [ .. | .... E ]
1418 [ .. | ..., E, ... ]
1419 [ .. | .... | ..., E | ... ]
1420 E :: Bool
1421 Translation: if E then fail else ...
1422
1423 A guard list, guarding a RHS of type rhs_ty
1424 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1425 * BodyStmt E BooParStmtBlockl: f x | ..., E, ... = ...rhs...
1426 E :: Bool
1427 Translation: if E then fail else ...
1428
1429 A monad comprehension of type (m res_ty)
1430 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1431 * BodyStmt E Bool: [ .. | .... E ]
1432 E :: Bool
1433 Translation: guard E >> ...
1434
1435 Array comprehensions are handled like list comprehensions.
1436
1437 Note [How RecStmt works]
1438 ~~~~~~~~~~~~~~~~~~~~~~~~
1439 Example:
1440 HsDo [ BindStmt x ex
1441
1442 , RecStmt { recS_rec_ids = [a, c]
1443 , recS_stmts = [ BindStmt b (return (a,c))
1444 , LetStmt a = ...b...
1445 , BindStmt c ec ]
1446 , recS_later_ids = [a, b]
1447
1448 , return (a b) ]
1449
1450 Here, the RecStmt binds a,b,c; but
1451 - Only a,b are used in the stmts *following* the RecStmt,
1452 - Only a,c are used in the stmts *inside* the RecStmt
1453 *before* their bindings
1454
1455 Why do we need *both* rec_ids and later_ids? For monads they could be
1456 combined into a single set of variables, but not for arrows. That
1457 follows from the types of the respective feedback operators:
1458
1459 mfix :: MonadFix m => (a -> m a) -> m a
1460 loop :: ArrowLoop a => a (b,d) (c,d) -> a b c
1461
1462 * For mfix, the 'a' covers the union of the later_ids and the rec_ids
1463 * For 'loop', 'c' is the later_ids and 'd' is the rec_ids
1464
1465 Note [Typing a RecStmt]
1466 ~~~~~~~~~~~~~~~~~~~~~~~
1467 A (RecStmt stmts) types as if you had written
1468
1469 (v1,..,vn, _, ..., _) <- mfix (\~(_, ..., _, r1, ..., rm) ->
1470 do { stmts
1471 ; return (v1,..vn, r1, ..., rm) })
1472
1473 where v1..vn are the later_ids
1474 r1..rm are the rec_ids
1475
1476 Note [Monad Comprehensions]
1477 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1478 Monad comprehensions require separate functions like 'return' and
1479 '>>=' for desugaring. These functions are stored in the statements
1480 used in monad comprehensions. For example, the 'return' of the 'LastStmt'
1481 expression is used to lift the body of the monad comprehension:
1482
1483 [ body | stmts ]
1484 =>
1485 stmts >>= \bndrs -> return body
1486
1487 In transform and grouping statements ('then ..' and 'then group ..') the
1488 'return' function is required for nested monad comprehensions, for example:
1489
1490 [ body | stmts, then f, rest ]
1491 =>
1492 f [ env | stmts ] >>= \bndrs -> [ body | rest ]
1493
1494 BodyStmts require the 'Control.Monad.guard' function for boolean
1495 expressions:
1496
1497 [ body | exp, stmts ]
1498 =>
1499 guard exp >> [ body | stmts ]
1500
1501 Parallel statements require the 'Control.Monad.Zip.mzip' function:
1502
1503 [ body | stmts1 | stmts2 | .. ]
1504 =>
1505 mzip stmts1 (mzip stmts2 (..)) >>= \(bndrs1, (bndrs2, ..)) -> return body
1506
1507 In any other context than 'MonadComp', the fields for most of these
1508 'SyntaxExpr's stay bottom.
1509 -}
1510
1511 instance (OutputableBndr idL)
1512 => Outputable (ParStmtBlock idL idR) where
1513 ppr (ParStmtBlock stmts _ _) = interpp'SP stmts
1514
1515 instance (OutputableBndr idL, OutputableBndr idR, Outputable body)
1516 => Outputable (StmtLR idL idR body) where
1517 ppr stmt = pprStmt stmt
1518
1519 pprStmt :: (OutputableBndr idL, OutputableBndr idR, Outputable body)
1520 => (StmtLR idL idR body) -> SDoc
1521 pprStmt (LastStmt expr _) = ifPprDebug (ptext (sLit "[last]")) <+> ppr expr
1522 pprStmt (BindStmt pat expr _ _) = hsep [ppr pat, larrow, ppr expr]
1523 pprStmt (LetStmt binds) = hsep [ptext (sLit "let"), pprBinds binds]
1524 pprStmt (BodyStmt expr _ _ _) = ppr expr
1525 pprStmt (ParStmt stmtss _ _) = sep (punctuate (ptext (sLit " | ")) (map ppr stmtss))
1526
1527 pprStmt (TransStmt { trS_stmts = stmts, trS_by = by, trS_using = using, trS_form = form })
1528 = sep $ punctuate comma (map ppr stmts ++ [pprTransStmt by using form])
1529
1530 pprStmt (RecStmt { recS_stmts = segment, recS_rec_ids = rec_ids
1531 , recS_later_ids = later_ids })
1532 = ptext (sLit "rec") <+>
1533 vcat [ ppr_do_stmts segment
1534 , ifPprDebug (vcat [ ptext (sLit "rec_ids=") <> ppr rec_ids
1535 , ptext (sLit "later_ids=") <> ppr later_ids])]
1536
1537 pprTransformStmt :: OutputableBndr id => [id] -> LHsExpr id -> Maybe (LHsExpr id) -> SDoc
1538 pprTransformStmt bndrs using by
1539 = sep [ ptext (sLit "then") <+> ifPprDebug (braces (ppr bndrs))
1540 , nest 2 (ppr using)
1541 , nest 2 (pprBy by)]
1542
1543 pprTransStmt :: Outputable body => Maybe body -> body -> TransForm -> SDoc
1544 pprTransStmt by using ThenForm
1545 = sep [ ptext (sLit "then"), nest 2 (ppr using), nest 2 (pprBy by)]
1546 pprTransStmt by using GroupForm
1547 = sep [ ptext (sLit "then group"), nest 2 (pprBy by), nest 2 (ptext (sLit "using") <+> ppr using)]
1548
1549 pprBy :: Outputable body => Maybe body -> SDoc
1550 pprBy Nothing = empty
1551 pprBy (Just e) = ptext (sLit "by") <+> ppr e
1552
1553 pprDo :: (OutputableBndr id, Outputable body)
1554 => HsStmtContext any -> [LStmt id body] -> SDoc
1555 pprDo DoExpr stmts = ptext (sLit "do") <+> ppr_do_stmts stmts
1556 pprDo GhciStmtCtxt stmts = ptext (sLit "do") <+> ppr_do_stmts stmts
1557 pprDo ArrowExpr stmts = ptext (sLit "do") <+> ppr_do_stmts stmts
1558 pprDo MDoExpr stmts = ptext (sLit "mdo") <+> ppr_do_stmts stmts
1559 pprDo ListComp stmts = brackets $ pprComp stmts
1560 pprDo PArrComp stmts = paBrackets $ pprComp stmts
1561 pprDo MonadComp stmts = brackets $ pprComp stmts
1562 pprDo _ _ = panic "pprDo" -- PatGuard, ParStmtCxt
1563
1564 ppr_do_stmts :: (OutputableBndr idL, OutputableBndr idR, Outputable body)
1565 => [LStmtLR idL idR body] -> SDoc
1566 -- Print a bunch of do stmts, with explicit braces and semicolons,
1567 -- so that we are not vulnerable to layout bugs
1568 ppr_do_stmts stmts
1569 = lbrace <+> pprDeeperList vcat (punctuate semi (map ppr stmts))
1570 <+> rbrace
1571
1572 pprComp :: (OutputableBndr id, Outputable body)
1573 => [LStmt id body] -> SDoc
1574 pprComp quals -- Prints: body | qual1, ..., qualn
1575 | not (null quals)
1576 , L _ (LastStmt body _) <- last quals
1577 = hang (ppr body <+> char '|') 2 (pprQuals (dropTail 1 quals))
1578 | otherwise
1579 = pprPanic "pprComp" (pprQuals quals)
1580
1581 pprQuals :: (OutputableBndr id, Outputable body)
1582 => [LStmt id body] -> SDoc
1583 -- Show list comprehension qualifiers separated by commas
1584 pprQuals quals = interpp'SP quals
1585
1586 {-
1587 ************************************************************************
1588 * *
1589 Template Haskell quotation brackets
1590 * *
1591 ************************************************************************
1592 -}
1593
1594 data HsSplice id
1595 = HsSplice -- $z or $(f 4)
1596 id -- A unique name to identify this splice point
1597 (LHsExpr id) -- See Note [Pending Splices]
1598 deriving (Typeable )
1599
1600 -- See Note [Pending Splices]
1601 data PendingSplice id
1602 = PendSplice Name (LHsExpr id)
1603 deriving( Typeable )
1604 -- It'd be convenient to re-use HsSplice, but the splice-name
1605 -- really is a Name, never an Id. Using (PostRn id Name) is
1606 -- nearly OK, but annoyingly we can't pretty-print it.
1607
1608 data PendingRnSplice
1609 = PendingRnExpSplice (PendingSplice Name)
1610 | PendingRnPatSplice (PendingSplice Name)
1611 | PendingRnTypeSplice (PendingSplice Name)
1612 | PendingRnDeclSplice (PendingSplice Name)
1613 | PendingRnCrossStageSplice Name
1614 deriving (Data, Typeable)
1615
1616 type PendingTcSplice = PendingSplice Id
1617
1618 deriving instance (DataId id) => Data (HsSplice id)
1619 deriving instance (DataId id) => Data (PendingSplice id)
1620
1621 {-
1622 Note [Pending Splices]
1623 ~~~~~~~~~~~~~~~~~~~~~~
1624 When we rename an untyped bracket, we name and lift out all the nested
1625 splices, so that when the typechecker hits the bracket, it can
1626 typecheck those nested splices without having to walk over the untyped
1627 bracket code. So for example
1628 [| f $(g x) |]
1629 looks like
1630
1631 HsBracket (HsApp (HsVar "f") (HsSpliceE _ (g x)))
1632
1633 which the renamer rewrites to
1634
1635 HsRnBracketOut (HsApp (HsVar f) (HsSpliceE sn (g x)))
1636 [PendingRnExpSplice (HsSplice sn (g x))]
1637
1638 * The 'sn' is the Name of the splice point.
1639
1640 * The PendingRnExpSplice gives the splice that splice-point name maps to;
1641 and the typechecker can now conveniently find these sub-expressions
1642
1643 * The other copy of the splice, in the second argument of HsSpliceE
1644 in the renamed first arg of HsRnBracketOut
1645 is used only for pretty printing
1646
1647 There are four varieties of pending splices generated by the renamer:
1648
1649 * Pending expression splices (PendingRnExpSplice), e.g.,
1650
1651 [|$(f x) + 2|]
1652
1653 * Pending pattern splices (PendingRnPatSplice), e.g.,
1654
1655 [|\ $(f x) -> x|]
1656
1657 * Pending type splices (PendingRnTypeSplice), e.g.,
1658
1659 [|f :: $(g x)|]
1660
1661 * Pending cross-stage splices (PendingRnCrossStageSplice), e.g.,
1662
1663 \x -> [| x |]
1664
1665 There is a fifth variety of pending splice, which is generated by the type
1666 checker:
1667
1668 * Pending *typed* expression splices, (PendingTcSplice), e.g.,
1669
1670 [||1 + $$(f 2)||]
1671
1672 It would be possible to eliminate HsRnBracketOut and use HsBracketOut for the
1673 output of the renamer. However, when pretty printing the output of the renamer,
1674 e.g., in a type error message, we *do not* want to print out the pending
1675 splices. In contrast, when pretty printing the output of the type checker, we
1676 *do* want to print the pending splices. So splitting them up seems to make
1677 sense, although I hate to add another constructor to HsExpr.
1678 -}
1679
1680 instance OutputableBndr id => Outputable (HsSplice id) where
1681 ppr (HsSplice n e) = angleBrackets (ppr n <> comma <+> ppr e)
1682
1683 instance OutputableBndr id => Outputable (PendingSplice id) where
1684 ppr (PendSplice n e) = angleBrackets (ppr n <> comma <+> ppr e)
1685
1686 pprUntypedSplice :: OutputableBndr id => HsSplice id -> SDoc
1687 pprUntypedSplice = pprSplice False
1688
1689 pprTypedSplice :: OutputableBndr id => HsSplice id -> SDoc
1690 pprTypedSplice = pprSplice True
1691
1692 pprSplice :: OutputableBndr id => Bool -> HsSplice id -> SDoc
1693 pprSplice is_typed (HsSplice n e)
1694 = (if is_typed then ptext (sLit "$$") else char '$')
1695 <> ifPprDebug (brackets (ppr n)) <> eDoc
1696 where
1697 -- We use pprLExpr to match pprParendExpr:
1698 -- Using pprLExpr makes sure that we go 'deeper'
1699 -- I think that is usually (always?) right
1700 pp_as_was = pprLExpr e
1701 eDoc = case unLoc e of
1702 HsPar _ -> pp_as_was
1703 HsVar _ -> pp_as_was
1704 _ -> parens pp_as_was
1705
1706 data HsBracket id = ExpBr (LHsExpr id) -- [| expr |]
1707 | PatBr (LPat id) -- [p| pat |]
1708 | DecBrL [LHsDecl id] -- [d| decls |]; result of parser
1709 | DecBrG (HsGroup id) -- [d| decls |]; result of renamer
1710 | TypBr (LHsType id) -- [t| type |]
1711 | VarBr Bool id -- True: 'x, False: ''T
1712 -- (The Bool flag is used only in pprHsBracket)
1713 | TExpBr (LHsExpr id) -- [|| expr ||]
1714 deriving (Typeable)
1715 deriving instance (DataId id) => Data (HsBracket id)
1716
1717 isTypedBracket :: HsBracket id -> Bool
1718 isTypedBracket (TExpBr {}) = True
1719 isTypedBracket _ = False
1720
1721 instance OutputableBndr id => Outputable (HsBracket id) where
1722 ppr = pprHsBracket
1723
1724
1725 pprHsBracket :: OutputableBndr id => HsBracket id -> SDoc
1726 pprHsBracket (ExpBr e) = thBrackets empty (ppr e)
1727 pprHsBracket (PatBr p) = thBrackets (char 'p') (ppr p)
1728 pprHsBracket (DecBrG gp) = thBrackets (char 'd') (ppr gp)
1729 pprHsBracket (DecBrL ds) = thBrackets (char 'd') (vcat (map ppr ds))
1730 pprHsBracket (TypBr t) = thBrackets (char 't') (ppr t)
1731 pprHsBracket (VarBr True n) = char '\'' <> ppr n
1732 pprHsBracket (VarBr False n) = ptext (sLit "''") <> ppr n
1733 pprHsBracket (TExpBr e) = thTyBrackets (ppr e)
1734
1735 thBrackets :: SDoc -> SDoc -> SDoc
1736 thBrackets pp_kind pp_body = char '[' <> pp_kind <> char '|' <+>
1737 pp_body <+> ptext (sLit "|]")
1738
1739 thTyBrackets :: SDoc -> SDoc
1740 thTyBrackets pp_body = ptext (sLit "[||") <+> pp_body <+> ptext (sLit "||]")
1741
1742 instance Outputable PendingRnSplice where
1743 ppr (PendingRnExpSplice s) = ppr s
1744 ppr (PendingRnPatSplice s) = ppr s
1745 ppr (PendingRnTypeSplice s) = ppr s
1746 ppr (PendingRnDeclSplice s) = ppr s
1747 ppr (PendingRnCrossStageSplice name) = ppr name
1748
1749 {-
1750 ************************************************************************
1751 * *
1752 \subsection{Enumerations and list comprehensions}
1753 * *
1754 ************************************************************************
1755 -}
1756
1757 data ArithSeqInfo id
1758 = From (LHsExpr id)
1759 | FromThen (LHsExpr id)
1760 (LHsExpr id)
1761 | FromTo (LHsExpr id)
1762 (LHsExpr id)
1763 | FromThenTo (LHsExpr id)
1764 (LHsExpr id)
1765 (LHsExpr id)
1766 deriving (Typeable)
1767 deriving instance (DataId id) => Data (ArithSeqInfo id)
1768
1769 instance OutputableBndr id => Outputable (ArithSeqInfo id) where
1770 ppr (From e1) = hcat [ppr e1, pp_dotdot]
1771 ppr (FromThen e1 e2) = hcat [ppr e1, comma, space, ppr e2, pp_dotdot]
1772 ppr (FromTo e1 e3) = hcat [ppr e1, pp_dotdot, ppr e3]
1773 ppr (FromThenTo e1 e2 e3)
1774 = hcat [ppr e1, comma, space, ppr e2, pp_dotdot, ppr e3]
1775
1776 pp_dotdot :: SDoc
1777 pp_dotdot = ptext (sLit " .. ")
1778
1779 {-
1780 ************************************************************************
1781 * *
1782 \subsection{HsMatchCtxt}
1783 * *
1784 ************************************************************************
1785 -}
1786
1787 data HsMatchContext id -- Context of a Match
1788 = FunRhs id Bool -- Function binding for f; True <=> written infix
1789 | LambdaExpr -- Patterns of a lambda
1790 | CaseAlt -- Patterns and guards on a case alternative
1791 | IfAlt -- Guards of a multi-way if alternative
1792 | ProcExpr -- Patterns of a proc
1793 | PatBindRhs -- A pattern binding eg [y] <- e = e
1794
1795 | RecUpd -- Record update [used only in DsExpr to
1796 -- tell matchWrapper what sort of
1797 -- runtime error message to generate]
1798
1799 | StmtCtxt (HsStmtContext id) -- Pattern of a do-stmt, list comprehension,
1800 -- pattern guard, etc
1801
1802 | ThPatSplice -- A Template Haskell pattern splice
1803 | ThPatQuote -- A Template Haskell pattern quotation [p| (a,b) |]
1804 | PatSyn -- A pattern synonym declaration
1805 deriving (Data, Typeable)
1806
1807 data HsStmtContext id
1808 = ListComp
1809 | MonadComp
1810 | PArrComp -- Parallel array comprehension
1811
1812 | DoExpr -- do { ... }
1813 | MDoExpr -- mdo { ... } ie recursive do-expression
1814 | ArrowExpr -- do-notation in an arrow-command context
1815
1816 | GhciStmtCtxt -- A command-line Stmt in GHCi pat <- rhs
1817 | PatGuard (HsMatchContext id) -- Pattern guard for specified thing
1818 | ParStmtCtxt (HsStmtContext id) -- A branch of a parallel stmt
1819 | TransStmtCtxt (HsStmtContext id) -- A branch of a transform stmt
1820 deriving (Data, Typeable)
1821
1822 isListCompExpr :: HsStmtContext id -> Bool
1823 -- Uses syntax [ e | quals ]
1824 isListCompExpr ListComp = True
1825 isListCompExpr PArrComp = True
1826 isListCompExpr MonadComp = True
1827 isListCompExpr (ParStmtCtxt c) = isListCompExpr c
1828 isListCompExpr (TransStmtCtxt c) = isListCompExpr c
1829 isListCompExpr _ = False
1830
1831 isMonadCompExpr :: HsStmtContext id -> Bool
1832 isMonadCompExpr MonadComp = True
1833 isMonadCompExpr (ParStmtCtxt ctxt) = isMonadCompExpr ctxt
1834 isMonadCompExpr (TransStmtCtxt ctxt) = isMonadCompExpr ctxt
1835 isMonadCompExpr _ = False
1836
1837 matchSeparator :: HsMatchContext id -> SDoc
1838 matchSeparator (FunRhs {}) = ptext (sLit "=")
1839 matchSeparator CaseAlt = ptext (sLit "->")
1840 matchSeparator IfAlt = ptext (sLit "->")
1841 matchSeparator LambdaExpr = ptext (sLit "->")
1842 matchSeparator ProcExpr = ptext (sLit "->")
1843 matchSeparator PatBindRhs = ptext (sLit "=")
1844 matchSeparator (StmtCtxt _) = ptext (sLit "<-")
1845 matchSeparator RecUpd = panic "unused"
1846 matchSeparator ThPatSplice = panic "unused"
1847 matchSeparator ThPatQuote = panic "unused"
1848 matchSeparator PatSyn = panic "unused"
1849
1850 pprMatchContext :: Outputable id => HsMatchContext id -> SDoc
1851 pprMatchContext ctxt
1852 | want_an ctxt = ptext (sLit "an") <+> pprMatchContextNoun ctxt
1853 | otherwise = ptext (sLit "a") <+> pprMatchContextNoun ctxt
1854 where
1855 want_an (FunRhs {}) = True -- Use "an" in front
1856 want_an ProcExpr = True
1857 want_an _ = False
1858
1859 pprMatchContextNoun :: Outputable id => HsMatchContext id -> SDoc
1860 pprMatchContextNoun (FunRhs fun _) = ptext (sLit "equation for")
1861 <+> quotes (ppr fun)
1862 pprMatchContextNoun CaseAlt = ptext (sLit "case alternative")
1863 pprMatchContextNoun IfAlt = ptext (sLit "multi-way if alternative")
1864 pprMatchContextNoun RecUpd = ptext (sLit "record-update construct")
1865 pprMatchContextNoun ThPatSplice = ptext (sLit "Template Haskell pattern splice")
1866 pprMatchContextNoun ThPatQuote = ptext (sLit "Template Haskell pattern quotation")
1867 pprMatchContextNoun PatBindRhs = ptext (sLit "pattern binding")
1868 pprMatchContextNoun LambdaExpr = ptext (sLit "lambda abstraction")
1869 pprMatchContextNoun ProcExpr = ptext (sLit "arrow abstraction")
1870 pprMatchContextNoun (StmtCtxt ctxt) = ptext (sLit "pattern binding in")
1871 $$ pprStmtContext ctxt
1872 pprMatchContextNoun PatSyn = ptext (sLit "pattern synonym declaration")
1873
1874 -----------------
1875 pprAStmtContext, pprStmtContext :: Outputable id => HsStmtContext id -> SDoc
1876 pprAStmtContext ctxt = article <+> pprStmtContext ctxt
1877 where
1878 pp_an = ptext (sLit "an")
1879 pp_a = ptext (sLit "a")
1880 article = case ctxt of
1881 MDoExpr -> pp_an
1882 PArrComp -> pp_an
1883 GhciStmtCtxt -> pp_an
1884 _ -> pp_a
1885
1886
1887 -----------------
1888 pprStmtContext GhciStmtCtxt = ptext (sLit "interactive GHCi command")
1889 pprStmtContext DoExpr = ptext (sLit "'do' block")
1890 pprStmtContext MDoExpr = ptext (sLit "'mdo' block")
1891 pprStmtContext ArrowExpr = ptext (sLit "'do' block in an arrow command")
1892 pprStmtContext ListComp = ptext (sLit "list comprehension")
1893 pprStmtContext MonadComp = ptext (sLit "monad comprehension")
1894 pprStmtContext PArrComp = ptext (sLit "array comprehension")
1895 pprStmtContext (PatGuard ctxt) = ptext (sLit "pattern guard for") $$ pprMatchContext ctxt
1896
1897 -- Drop the inner contexts when reporting errors, else we get
1898 -- Unexpected transform statement
1899 -- in a transformed branch of
1900 -- transformed branch of
1901 -- transformed branch of monad comprehension
1902 pprStmtContext (ParStmtCtxt c)
1903 | opt_PprStyle_Debug = sep [ptext (sLit "parallel branch of"), pprAStmtContext c]
1904 | otherwise = pprStmtContext c
1905 pprStmtContext (TransStmtCtxt c)
1906 | opt_PprStyle_Debug = sep [ptext (sLit "transformed branch of"), pprAStmtContext c]
1907 | otherwise = pprStmtContext c
1908
1909
1910 -- Used to generate the string for a *runtime* error message
1911 matchContextErrString :: Outputable id => HsMatchContext id -> SDoc
1912 matchContextErrString (FunRhs fun _) = ptext (sLit "function") <+> ppr fun
1913 matchContextErrString CaseAlt = ptext (sLit "case")
1914 matchContextErrString IfAlt = ptext (sLit "multi-way if")
1915 matchContextErrString PatBindRhs = ptext (sLit "pattern binding")
1916 matchContextErrString RecUpd = ptext (sLit "record update")
1917 matchContextErrString LambdaExpr = ptext (sLit "lambda")
1918 matchContextErrString ProcExpr = ptext (sLit "proc")
1919 matchContextErrString ThPatSplice = panic "matchContextErrString" -- Not used at runtime
1920 matchContextErrString ThPatQuote = panic "matchContextErrString" -- Not used at runtime
1921 matchContextErrString PatSyn = panic "matchContextErrString" -- Not used at runtime
1922 matchContextErrString (StmtCtxt (ParStmtCtxt c)) = matchContextErrString (StmtCtxt c)
1923 matchContextErrString (StmtCtxt (TransStmtCtxt c)) = matchContextErrString (StmtCtxt c)
1924 matchContextErrString (StmtCtxt (PatGuard _)) = ptext (sLit "pattern guard")
1925 matchContextErrString (StmtCtxt GhciStmtCtxt) = ptext (sLit "interactive GHCi command")
1926 matchContextErrString (StmtCtxt DoExpr) = ptext (sLit "'do' block")
1927 matchContextErrString (StmtCtxt ArrowExpr) = ptext (sLit "'do' block")
1928 matchContextErrString (StmtCtxt MDoExpr) = ptext (sLit "'mdo' block")
1929 matchContextErrString (StmtCtxt ListComp) = ptext (sLit "list comprehension")
1930 matchContextErrString (StmtCtxt MonadComp) = ptext (sLit "monad comprehension")
1931 matchContextErrString (StmtCtxt PArrComp) = ptext (sLit "array comprehension")
1932
1933 pprMatchInCtxt :: (OutputableBndr idL, OutputableBndr idR, Outputable body)
1934 => HsMatchContext idL -> Match idR body -> SDoc
1935 pprMatchInCtxt ctxt match = hang (ptext (sLit "In") <+> pprMatchContext ctxt <> colon)
1936 4 (pprMatch ctxt match)
1937
1938 pprStmtInCtxt :: (OutputableBndr idL, OutputableBndr idR, Outputable body)
1939 => HsStmtContext idL -> StmtLR idL idR body -> SDoc
1940 pprStmtInCtxt ctxt (LastStmt e _)
1941 | isListCompExpr ctxt -- For [ e | .. ], do not mutter about "stmts"
1942 = hang (ptext (sLit "In the expression:")) 2 (ppr e)
1943
1944 pprStmtInCtxt ctxt stmt
1945 = hang (ptext (sLit "In a stmt of") <+> pprAStmtContext ctxt <> colon)
1946 2 (ppr_stmt stmt)
1947 where
1948 -- For Group and Transform Stmts, don't print the nested stmts!
1949 ppr_stmt (TransStmt { trS_by = by, trS_using = using
1950 , trS_form = form }) = pprTransStmt by using form
1951 ppr_stmt stmt = pprStmt stmt