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