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