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