Refactor visible type application.
[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 = aexp, rupd_flds = rbinds })
795 = hang (pprLExpr 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 (RecordCon {}) = False
935 hsExprNeedsParens (RecordUpd {}) = False
936 hsExprNeedsParens (HsPar {}) = False
937 hsExprNeedsParens (HsBracket {}) = False
938 hsExprNeedsParens (HsRnBracketOut {}) = False
939 hsExprNeedsParens (HsTcBracketOut {}) = False
940 hsExprNeedsParens (HsDo sc _ _)
941 | isListCompExpr sc = False
942 hsExprNeedsParens (HsRecFld{}) = False
943 hsExprNeedsParens _ = True
944
945
946 isAtomicHsExpr :: HsExpr id -> Bool
947 -- True of a single token
948 isAtomicHsExpr (HsVar {}) = True
949 isAtomicHsExpr (HsLit {}) = True
950 isAtomicHsExpr (HsOverLit {}) = True
951 isAtomicHsExpr (HsIPVar {}) = True
952 isAtomicHsExpr (HsOverLabel {}) = True
953 isAtomicHsExpr (HsUnboundVar {}) = True
954 isAtomicHsExpr (HsWrap _ e) = isAtomicHsExpr e
955 isAtomicHsExpr (HsPar e) = isAtomicHsExpr (unLoc e)
956 isAtomicHsExpr (HsRecFld{}) = True
957 isAtomicHsExpr _ = False
958
959 {-
960 ************************************************************************
961 * *
962 \subsection{Commands (in arrow abstractions)}
963 * *
964 ************************************************************************
965
966 We re-use HsExpr to represent these.
967 -}
968
969 type LHsCmd id = Located (HsCmd id)
970
971 data HsCmd id
972 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.Annlarrowtail',
973 -- 'ApiAnnotation.Annrarrowtail','ApiAnnotation.AnnLarrowtail',
974 -- 'ApiAnnotation.AnnRarrowtail'
975
976 -- For details on above see note [Api annotations] in ApiAnnotation
977 = HsCmdArrApp -- Arrow tail, or arrow application (f -< arg)
978 (LHsExpr id) -- arrow expression, f
979 (LHsExpr id) -- input expression, arg
980 (PostTc id Type) -- type of the arrow expressions f,
981 -- of the form a t t', where arg :: t
982 HsArrAppType -- higher-order (-<<) or first-order (-<)
983 Bool -- True => right-to-left (f -< arg)
984 -- False => left-to-right (arg >- f)
985
986 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'(|'@,
987 -- 'ApiAnnotation.AnnClose' @'|)'@
988
989 -- For details on above see note [Api annotations] in ApiAnnotation
990 | HsCmdArrForm -- Command formation, (| e cmd1 .. cmdn |)
991 (LHsExpr id) -- the operator
992 -- after type-checking, a type abstraction to be
993 -- applied to the type of the local environment tuple
994 (Maybe Fixity) -- fixity (filled in by the renamer), for forms that
995 -- were converted from OpApp's by the renamer
996 [LHsCmdTop id] -- argument commands
997
998 | HsCmdApp (LHsCmd id)
999 (LHsExpr id)
1000
1001 | HsCmdLam (MatchGroup id (LHsCmd id)) -- kappa
1002 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLam',
1003 -- 'ApiAnnotation.AnnRarrow',
1004
1005 -- For details on above see note [Api annotations] in ApiAnnotation
1006
1007 | HsCmdPar (LHsCmd id) -- parenthesised command
1008 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@,
1009 -- 'ApiAnnotation.AnnClose' @')'@
1010
1011 -- For details on above see note [Api annotations] in ApiAnnotation
1012
1013 | HsCmdCase (LHsExpr id)
1014 (MatchGroup id (LHsCmd id)) -- bodies are HsCmd's
1015 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnCase',
1016 -- 'ApiAnnotation.AnnOf','ApiAnnotation.AnnOpen' @'{'@,
1017 -- 'ApiAnnotation.AnnClose' @'}'@
1018
1019 -- For details on above see note [Api annotations] in ApiAnnotation
1020
1021 | HsCmdIf (Maybe (SyntaxExpr id)) -- cond function
1022 (LHsExpr id) -- predicate
1023 (LHsCmd id) -- then part
1024 (LHsCmd id) -- else part
1025 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnIf',
1026 -- 'ApiAnnotation.AnnSemi',
1027 -- 'ApiAnnotation.AnnThen','ApiAnnotation.AnnSemi',
1028 -- 'ApiAnnotation.AnnElse',
1029
1030 -- For details on above see note [Api annotations] in ApiAnnotation
1031
1032 | HsCmdLet (Located (HsLocalBinds id)) -- let(rec)
1033 (LHsCmd id)
1034 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLet',
1035 -- 'ApiAnnotation.AnnOpen' @'{'@,
1036 -- 'ApiAnnotation.AnnClose' @'}'@,'ApiAnnotation.AnnIn'
1037
1038 -- For details on above see note [Api annotations] in ApiAnnotation
1039
1040 | HsCmdDo (Located [CmdLStmt id])
1041 (PostTc id Type) -- Type of the whole expression
1042 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDo',
1043 -- 'ApiAnnotation.AnnOpen', 'ApiAnnotation.AnnSemi',
1044 -- 'ApiAnnotation.AnnVbar',
1045 -- 'ApiAnnotation.AnnClose'
1046
1047 -- For details on above see note [Api annotations] in ApiAnnotation
1048
1049 | HsCmdWrap HsWrapper
1050 (HsCmd id) -- If cmd :: arg1 --> res
1051 -- wrap :: arg1 "->" arg2
1052 -- Then (HsCmdWrap wrap cmd) :: arg2 --> res
1053 deriving (Typeable)
1054 deriving instance (DataId id) => Data (HsCmd id)
1055
1056 data HsArrAppType = HsHigherOrderApp | HsFirstOrderApp
1057 deriving (Data, Typeable)
1058
1059
1060 {- | Top-level command, introducing a new arrow.
1061 This may occur inside a proc (where the stack is empty) or as an
1062 argument of a command-forming operator.
1063 -}
1064
1065 type LHsCmdTop id = Located (HsCmdTop id)
1066
1067 data HsCmdTop id
1068 = HsCmdTop (LHsCmd id)
1069 (PostTc id Type) -- Nested tuple of inputs on the command's stack
1070 (PostTc id Type) -- return type of the command
1071 (CmdSyntaxTable id) -- See Note [CmdSyntaxTable]
1072 deriving (Typeable)
1073 deriving instance (DataId id) => Data (HsCmdTop id)
1074
1075 instance OutputableBndr id => Outputable (HsCmd id) where
1076 ppr cmd = pprCmd cmd
1077
1078 -----------------------
1079 -- pprCmd and pprLCmd call pprDeeper;
1080 -- the underscore versions do not
1081 pprLCmd :: OutputableBndr id => LHsCmd id -> SDoc
1082 pprLCmd (L _ c) = pprCmd c
1083
1084 pprCmd :: OutputableBndr id => HsCmd id -> SDoc
1085 pprCmd c | isQuietHsCmd c = ppr_cmd c
1086 | otherwise = pprDeeper (ppr_cmd c)
1087
1088 isQuietHsCmd :: HsCmd id -> Bool
1089 -- Parentheses do display something, but it gives little info and
1090 -- if we go deeper when we go inside them then we get ugly things
1091 -- like (...)
1092 isQuietHsCmd (HsCmdPar _) = True
1093 -- applications don't display anything themselves
1094 isQuietHsCmd (HsCmdApp _ _) = True
1095 isQuietHsCmd _ = False
1096
1097 -----------------------
1098 ppr_lcmd :: OutputableBndr id => LHsCmd id -> SDoc
1099 ppr_lcmd c = ppr_cmd (unLoc c)
1100
1101 ppr_cmd :: forall id. OutputableBndr id => HsCmd id -> SDoc
1102 ppr_cmd (HsCmdPar c) = parens (ppr_lcmd c)
1103
1104 ppr_cmd (HsCmdApp c e)
1105 = let (fun, args) = collect_args c [e] in
1106 hang (ppr_lcmd fun) 2 (sep (map pprParendLExpr args))
1107 where
1108 collect_args (L _ (HsCmdApp fun arg)) args = collect_args fun (arg:args)
1109 collect_args fun args = (fun, args)
1110
1111 ppr_cmd (HsCmdLam matches)
1112 = pprMatches (LambdaExpr :: HsMatchContext id) matches
1113
1114 ppr_cmd (HsCmdCase expr matches)
1115 = sep [ sep [text "case", nest 4 (ppr expr), ptext (sLit "of {")],
1116 nest 2 (pprMatches (CaseAlt :: HsMatchContext id) matches <+> char '}') ]
1117
1118 ppr_cmd (HsCmdIf _ e ct ce)
1119 = sep [hsep [text "if", nest 2 (ppr e), ptext (sLit "then")],
1120 nest 4 (ppr ct),
1121 text "else",
1122 nest 4 (ppr ce)]
1123
1124 -- special case: let ... in let ...
1125 ppr_cmd (HsCmdLet (L _ binds) cmd@(L _ (HsCmdLet _ _)))
1126 = sep [hang (text "let") 2 (hsep [pprBinds binds, ptext (sLit "in")]),
1127 ppr_lcmd cmd]
1128
1129 ppr_cmd (HsCmdLet (L _ binds) cmd)
1130 = sep [hang (text "let") 2 (pprBinds binds),
1131 hang (text "in") 2 (ppr cmd)]
1132
1133 ppr_cmd (HsCmdDo (L _ stmts) _) = pprDo ArrowExpr stmts
1134
1135 ppr_cmd (HsCmdWrap w cmd)
1136 = pprHsWrapper w (\_ -> parens (ppr_cmd cmd))
1137 ppr_cmd (HsCmdArrApp arrow arg _ HsFirstOrderApp True)
1138 = hsep [ppr_lexpr arrow, larrowt, ppr_lexpr arg]
1139 ppr_cmd (HsCmdArrApp arrow arg _ HsFirstOrderApp False)
1140 = hsep [ppr_lexpr arg, arrowt, ppr_lexpr arrow]
1141 ppr_cmd (HsCmdArrApp arrow arg _ HsHigherOrderApp True)
1142 = hsep [ppr_lexpr arrow, larrowtt, ppr_lexpr arg]
1143 ppr_cmd (HsCmdArrApp arrow arg _ HsHigherOrderApp False)
1144 = hsep [ppr_lexpr arg, arrowtt, ppr_lexpr arrow]
1145
1146 ppr_cmd (HsCmdArrForm (L _ (HsVar (L _ v))) (Just _) [arg1, arg2])
1147 = sep [pprCmdArg (unLoc arg1), hsep [pprInfixOcc v, pprCmdArg (unLoc arg2)]]
1148 ppr_cmd (HsCmdArrForm op _ args)
1149 = hang (text "(|" <> ppr_lexpr op)
1150 4 (sep (map (pprCmdArg.unLoc) args) <> text "|)")
1151
1152 pprCmdArg :: OutputableBndr id => HsCmdTop id -> SDoc
1153 pprCmdArg (HsCmdTop cmd@(L _ (HsCmdArrForm _ Nothing [])) _ _ _)
1154 = ppr_lcmd cmd
1155 pprCmdArg (HsCmdTop cmd _ _ _)
1156 = parens (ppr_lcmd cmd)
1157
1158 instance OutputableBndr id => Outputable (HsCmdTop id) where
1159 ppr = pprCmdArg
1160
1161 {-
1162 ************************************************************************
1163 * *
1164 \subsection{Record binds}
1165 * *
1166 ************************************************************************
1167 -}
1168
1169 type HsRecordBinds id = HsRecFields id (LHsExpr id)
1170
1171 {-
1172 ************************************************************************
1173 * *
1174 \subsection{@Match@, @GRHSs@, and @GRHS@ datatypes}
1175 * *
1176 ************************************************************************
1177
1178 @Match@es are sets of pattern bindings and right hand sides for
1179 functions, patterns or case branches. For example, if a function @g@
1180 is defined as:
1181 \begin{verbatim}
1182 g (x,y) = y
1183 g ((x:ys),y) = y+1,
1184 \end{verbatim}
1185 then \tr{g} has two @Match@es: @(x,y) = y@ and @((x:ys),y) = y+1@.
1186
1187 It is always the case that each element of an @[Match]@ list has the
1188 same number of @pats@s inside it. This corresponds to saying that
1189 a function defined by pattern matching must have the same number of
1190 patterns in each equation.
1191 -}
1192
1193 data MatchGroup id body
1194 = MG { mg_alts :: Located [LMatch id body] -- The alternatives
1195 , mg_arg_tys :: [PostTc id Type] -- Types of the arguments, t1..tn
1196 , mg_res_ty :: PostTc id Type -- Type of the result, tr
1197 , mg_origin :: Origin }
1198 -- The type is the type of the entire group
1199 -- t1 -> ... -> tn -> tr
1200 -- where there are n patterns
1201 deriving (Typeable)
1202 deriving instance (Data body,DataId id) => Data (MatchGroup id body)
1203
1204 type LMatch id body = Located (Match id body)
1205 -- ^ May have 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnSemi' when in a
1206 -- list
1207
1208 -- For details on above see note [Api annotations] in ApiAnnotation
1209 data Match id body
1210 = Match {
1211 m_fixity :: MatchFixity id,
1212 -- See note [m_fixity in Match]
1213 m_pats :: [LPat id], -- The patterns
1214 m_type :: (Maybe (LHsType id)),
1215 -- A type signature for the result of the match
1216 -- Nothing after typechecking
1217 -- NB: No longer supported
1218 m_grhss :: (GRHSs id body)
1219 } deriving (Typeable)
1220 deriving instance (Data body,DataId id) => Data (Match id body)
1221
1222 {-
1223 Note [m_fixity in Match]
1224 ~~~~~~~~~~~~~~~~~~~~~~
1225
1226 The parser initially creates a FunBind with a single Match in it for
1227 every function definition it sees.
1228
1229 These are then grouped together by getMonoBind into a single FunBind,
1230 where all the Matches are combined.
1231
1232 In the process, all the original FunBind fun_id's bar one are
1233 discarded, including the locations.
1234
1235 This causes a problem for source to source conversions via API
1236 Annotations, so the original fun_ids and infix flags are preserved in
1237 the Match, when it originates from a FunBind.
1238
1239 Example infix function definition requiring individual API Annotations
1240
1241 (&&& ) [] [] = []
1242 xs &&& [] = xs
1243 ( &&& ) [] ys = ys
1244
1245
1246 -}
1247
1248 -- |When a Match is part of a FunBind, it captures one complete equation for the
1249 -- function. As such it has the function name, and its fixity.
1250 data MatchFixity id
1251 = NonFunBindMatch
1252 | FunBindMatch (Located id) -- of the Id
1253 Bool -- is infix
1254 deriving (Typeable)
1255 deriving instance (DataId id) => Data (MatchFixity id)
1256
1257 isInfixMatch :: Match id body -> Bool
1258 isInfixMatch match = case m_fixity match of
1259 FunBindMatch _ True -> True
1260 _ -> False
1261
1262 isEmptyMatchGroup :: MatchGroup id body -> Bool
1263 isEmptyMatchGroup (MG { mg_alts = ms }) = null $ unLoc ms
1264
1265 -- | Is there only one RHS in this group?
1266 isSingletonMatchGroup :: MatchGroup id body -> Bool
1267 isSingletonMatchGroup (MG { mg_alts = L _ [match] })
1268 | L _ (Match { m_grhss = GRHSs { grhssGRHSs = [_] } }) <- match
1269 = True
1270 isSingletonMatchGroup _ = False
1271
1272 matchGroupArity :: MatchGroup id body -> Arity
1273 -- Precondition: MatchGroup is non-empty
1274 -- This is called before type checking, when mg_arg_tys is not set
1275 matchGroupArity (MG { mg_alts = alts })
1276 | L _ (alt1:_) <- alts = length (hsLMatchPats alt1)
1277 | otherwise = panic "matchGroupArity"
1278
1279 hsLMatchPats :: LMatch id body -> [LPat id]
1280 hsLMatchPats (L _ (Match _ pats _ _)) = pats
1281
1282 -- | GRHSs are used both for pattern bindings and for Matches
1283 --
1284 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnVbar',
1285 -- 'ApiAnnotation.AnnEqual','ApiAnnotation.AnnWhere',
1286 -- 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose'
1287 -- 'ApiAnnotation.AnnRarrow','ApiAnnotation.AnnSemi'
1288
1289 -- For details on above see note [Api annotations] in ApiAnnotation
1290 data GRHSs id body
1291 = GRHSs {
1292 grhssGRHSs :: [LGRHS id body], -- ^ Guarded RHSs
1293 grhssLocalBinds :: Located (HsLocalBinds id) -- ^ The where clause
1294 } deriving (Typeable)
1295 deriving instance (Data body,DataId id) => Data (GRHSs id body)
1296
1297 type LGRHS id body = Located (GRHS id body)
1298
1299 -- | Guarded Right Hand Side.
1300 data GRHS id body = GRHS [GuardLStmt id] -- Guards
1301 body -- Right hand side
1302 deriving (Typeable)
1303 deriving instance (Data body,DataId id) => Data (GRHS id body)
1304
1305 -- We know the list must have at least one @Match@ in it.
1306
1307 pprMatches :: (OutputableBndr idL, OutputableBndr idR, Outputable body)
1308 => HsMatchContext idL -> MatchGroup idR body -> SDoc
1309 pprMatches ctxt (MG { mg_alts = matches })
1310 = vcat (map (pprMatch ctxt) (map unLoc (unLoc matches)))
1311 -- Don't print the type; it's only a place-holder before typechecking
1312
1313 -- Exported to HsBinds, which can't see the defn of HsMatchContext
1314 pprFunBind :: (OutputableBndr idL, OutputableBndr idR, Outputable body)
1315 => idL -> MatchGroup idR body -> SDoc
1316 pprFunBind fun matches = pprMatches (FunRhs fun) matches
1317
1318 -- Exported to HsBinds, which can't see the defn of HsMatchContext
1319 pprPatBind :: forall bndr id body. (OutputableBndr bndr, OutputableBndr id, Outputable body)
1320 => LPat bndr -> GRHSs id body -> SDoc
1321 pprPatBind pat (grhss)
1322 = sep [ppr pat, nest 2 (pprGRHSs (PatBindRhs :: HsMatchContext id) grhss)]
1323
1324 pprMatch :: (OutputableBndr idL, OutputableBndr idR, Outputable body)
1325 => HsMatchContext idL -> Match idR body -> SDoc
1326 pprMatch ctxt match
1327 = sep [ sep (herald : map (nest 2 . pprParendLPat) other_pats)
1328 , nest 2 ppr_maybe_ty
1329 , nest 2 (pprGRHSs ctxt (m_grhss match)) ]
1330 where
1331 is_infix = isInfixMatch match
1332 (herald, other_pats)
1333 = case ctxt of
1334 FunRhs fun
1335 | not is_infix -> (pprPrefixOcc fun, m_pats match)
1336 -- f x y z = e
1337 -- Not pprBndr; the AbsBinds will
1338 -- have printed the signature
1339
1340 | null pats2 -> (pp_infix, [])
1341 -- x &&& y = e
1342
1343 | otherwise -> (parens pp_infix, pats2)
1344 -- (x &&& y) z = e
1345 where
1346 pp_infix = pprParendLPat pat1 <+> pprInfixOcc fun <+> pprParendLPat pat2
1347
1348 LambdaExpr -> (char '\\', m_pats match)
1349
1350 _ -> ASSERT( null pats1 )
1351 (ppr pat1, []) -- No parens around the single pat
1352
1353 (pat1:pats1) = m_pats match
1354 (pat2:pats2) = pats1
1355 ppr_maybe_ty = case m_type match of
1356 Just ty -> dcolon <+> ppr ty
1357 Nothing -> empty
1358
1359
1360 pprGRHSs :: (OutputableBndr idR, Outputable body)
1361 => HsMatchContext idL -> GRHSs idR body -> SDoc
1362 pprGRHSs ctxt (GRHSs grhss (L _ binds))
1363 = vcat (map (pprGRHS ctxt . unLoc) grhss)
1364 $$ ppUnless (isEmptyLocalBinds binds)
1365 (text "where" $$ nest 4 (pprBinds binds))
1366
1367 pprGRHS :: (OutputableBndr idR, Outputable body)
1368 => HsMatchContext idL -> GRHS idR body -> SDoc
1369 pprGRHS ctxt (GRHS [] body)
1370 = pp_rhs ctxt body
1371
1372 pprGRHS ctxt (GRHS guards body)
1373 = sep [vbar <+> interpp'SP guards, pp_rhs ctxt body]
1374
1375 pp_rhs :: Outputable body => HsMatchContext idL -> body -> SDoc
1376 pp_rhs ctxt rhs = matchSeparator ctxt <+> pprDeeper (ppr rhs)
1377
1378 {-
1379 ************************************************************************
1380 * *
1381 \subsection{Do stmts and list comprehensions}
1382 * *
1383 ************************************************************************
1384 -}
1385
1386 type LStmt id body = Located (StmtLR id id body)
1387 type LStmtLR idL idR body = Located (StmtLR idL idR body)
1388
1389 type Stmt id body = StmtLR id id body
1390
1391 type CmdLStmt id = LStmt id (LHsCmd id)
1392 type CmdStmt id = Stmt id (LHsCmd id)
1393 type ExprLStmt id = LStmt id (LHsExpr id)
1394 type ExprStmt id = Stmt id (LHsExpr id)
1395
1396 type GuardLStmt id = LStmt id (LHsExpr id)
1397 type GuardStmt id = Stmt id (LHsExpr id)
1398 type GhciLStmt id = LStmt id (LHsExpr id)
1399 type GhciStmt id = Stmt id (LHsExpr id)
1400
1401 -- The SyntaxExprs in here are used *only* for do-notation and monad
1402 -- comprehensions, which have rebindable syntax. Otherwise they are unused.
1403 -- | API Annotations when in qualifier lists or guards
1404 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnVbar',
1405 -- 'ApiAnnotation.AnnComma','ApiAnnotation.AnnThen',
1406 -- 'ApiAnnotation.AnnBy','ApiAnnotation.AnnBy',
1407 -- 'ApiAnnotation.AnnGroup','ApiAnnotation.AnnUsing'
1408
1409 -- For details on above see note [Api annotations] in ApiAnnotation
1410 data StmtLR idL idR body -- body should always be (LHs**** idR)
1411 = LastStmt -- Always the last Stmt in ListComp, MonadComp, PArrComp,
1412 -- and (after the renamer) DoExpr, MDoExpr
1413 -- Not used for GhciStmtCtxt, PatGuard, which scope over other stuff
1414 body
1415 Bool -- True <=> return was stripped by ApplicativeDo
1416 (SyntaxExpr idR) -- The return operator, used only for
1417 -- MonadComp For ListComp, PArrComp, we
1418 -- use the baked-in 'return' For DoExpr,
1419 -- MDoExpr, we don't apply a 'return' at
1420 -- all See Note [Monad Comprehensions] |
1421 -- - 'ApiAnnotation.AnnKeywordId' :
1422 -- 'ApiAnnotation.AnnLarrow'
1423
1424 -- For details on above see note [Api annotations] in ApiAnnotation
1425 | BindStmt (LPat idL)
1426 body
1427 (SyntaxExpr idR) -- The (>>=) operator; see Note [The type of bind in Stmts]
1428 (SyntaxExpr idR) -- The fail operator
1429 -- The fail operator is noSyntaxExpr
1430 -- if the pattern match can't fail
1431
1432 (PostTc idR Type) -- result type of the function passed to bind;
1433 -- that is, S in (>>=) :: Q -> (R -> S) -> T
1434
1435 -- | 'ApplicativeStmt' represents an applicative expression built with
1436 -- <$> and <*>. It is generated by the renamer, and is desugared into the
1437 -- appropriate applicative expression by the desugarer, but it is intended
1438 -- to be invisible in error messages.
1439 --
1440 -- For full details, see Note [ApplicativeDo] in RnExpr
1441 --
1442 | ApplicativeStmt
1443 [ ( SyntaxExpr idR
1444 , ApplicativeArg idL idR) ]
1445 -- [(<$>, e1), (<*>, e2), ..., (<*>, en)]
1446 (Maybe (SyntaxExpr idR)) -- 'join', if necessary
1447 (PostTc idR Type) -- Type of the body
1448
1449 | BodyStmt body -- See Note [BodyStmt]
1450 (SyntaxExpr idR) -- The (>>) operator
1451 (SyntaxExpr idR) -- The `guard` operator; used only in MonadComp
1452 -- See notes [Monad Comprehensions]
1453 (PostTc idR Type) -- Element type of the RHS (used for arrows)
1454
1455 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLet'
1456 -- 'ApiAnnotation.AnnOpen' @'{'@,'ApiAnnotation.AnnClose' @'}'@,
1457
1458 -- For details on above see note [Api annotations] in ApiAnnotation
1459 | LetStmt (Located (HsLocalBindsLR idL idR))
1460
1461 -- ParStmts only occur in a list/monad comprehension
1462 | ParStmt [ParStmtBlock idL idR]
1463 (HsExpr idR) -- Polymorphic `mzip` for monad comprehensions
1464 (SyntaxExpr idR) -- The `>>=` operator
1465 -- See notes [Monad Comprehensions]
1466 (PostTc idR Type) -- S in (>>=) :: Q -> (R -> S) -> T
1467 -- After renaming, the ids are the binders
1468 -- bound by the stmts and used after themp
1469
1470 | TransStmt {
1471 trS_form :: TransForm,
1472 trS_stmts :: [ExprLStmt idL], -- Stmts to the *left* of the 'group'
1473 -- which generates the tuples to be grouped
1474
1475 trS_bndrs :: [(idR, idR)], -- See Note [TransStmt binder map]
1476
1477 trS_using :: LHsExpr idR,
1478 trS_by :: Maybe (LHsExpr idR), -- "by e" (optional)
1479 -- Invariant: if trS_form = GroupBy, then grp_by = Just e
1480
1481 trS_ret :: SyntaxExpr idR, -- The monomorphic 'return' function for
1482 -- the inner monad comprehensions
1483 trS_bind :: SyntaxExpr idR, -- The '(>>=)' operator
1484 trS_bind_arg_ty :: PostTc idR Type, -- R in (>>=) :: Q -> (R -> S) -> T
1485 trS_fmap :: HsExpr idR -- The polymorphic 'fmap' function for desugaring
1486 -- Only for 'group' forms
1487 -- Just a simple HsExpr, because it's
1488 -- too polymorphic for tcSyntaxOp
1489 } -- See Note [Monad Comprehensions]
1490
1491 -- Recursive statement (see Note [How RecStmt works] below)
1492 -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnRec'
1493
1494 -- For details on above see note [Api annotations] in ApiAnnotation
1495 | RecStmt
1496 { recS_stmts :: [LStmtLR idL idR body]
1497
1498 -- The next two fields are only valid after renaming
1499 , recS_later_ids :: [idR] -- The ids are a subset of the variables bound by the
1500 -- stmts that are used in stmts that follow the RecStmt
1501
1502 , recS_rec_ids :: [idR] -- Ditto, but these variables are the "recursive" ones,
1503 -- that are used before they are bound in the stmts of
1504 -- the RecStmt.
1505 -- An Id can be in both groups
1506 -- Both sets of Ids are (now) treated monomorphically
1507 -- See Note [How RecStmt works] for why they are separate
1508
1509 -- Rebindable syntax
1510 , recS_bind_fn :: SyntaxExpr idR -- The bind function
1511 , recS_ret_fn :: SyntaxExpr idR -- The return function
1512 , recS_mfix_fn :: SyntaxExpr idR -- The mfix function
1513 , recS_bind_ty :: PostTc idR Type -- S in (>>=) :: Q -> (R -> S) -> T
1514
1515 -- These fields are only valid after typechecking
1516 , recS_later_rets :: [PostTcExpr] -- (only used in the arrow version)
1517 , recS_rec_rets :: [PostTcExpr] -- These expressions correspond 1-to-1
1518 -- with recS_later_ids and recS_rec_ids,
1519 -- and are the expressions that should be
1520 -- returned by the recursion.
1521 -- They may not quite be the Ids themselves,
1522 -- because the Id may be *polymorphic*, but
1523 -- the returned thing has to be *monomorphic*,
1524 -- so they may be type applications
1525
1526 , recS_ret_ty :: PostTc idR Type -- The type of
1527 -- do { stmts; return (a,b,c) }
1528 -- With rebindable syntax the type might not
1529 -- be quite as simple as (m (tya, tyb, tyc)).
1530 }
1531 deriving (Typeable)
1532 deriving instance (Data body, DataId idL, DataId idR)
1533 => Data (StmtLR idL idR body)
1534
1535 data TransForm -- The 'f' below is the 'using' function, 'e' is the by function
1536 = ThenForm -- then f or then f by e (depending on trS_by)
1537 | GroupForm -- then group using f or then group by e using f (depending on trS_by)
1538 deriving (Data, Typeable)
1539
1540 data ParStmtBlock idL idR
1541 = ParStmtBlock
1542 [ExprLStmt idL]
1543 [idR] -- The variables to be returned
1544 (SyntaxExpr idR) -- The return operator
1545 deriving( Typeable )
1546 deriving instance (DataId idL, DataId idR) => Data (ParStmtBlock idL idR)
1547
1548 data ApplicativeArg idL idR
1549 = ApplicativeArgOne -- pat <- expr (pat must be irrefutable)
1550 (LPat idL)
1551 (LHsExpr idL)
1552 | ApplicativeArgMany -- do { stmts; return vars }
1553 [ExprLStmt idL] -- stmts
1554 (HsExpr idL) -- return (v1,..,vn), or just (v1,..,vn)
1555 (LPat idL) -- (v1,...,vn)
1556 deriving( Typeable )
1557 deriving instance (DataId idL, DataId idR) => Data (ApplicativeArg idL idR)
1558
1559 {-
1560 Note [The type of bind in Stmts]
1561 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1562 Some Stmts, notably BindStmt, keep the (>>=) bind operator.
1563 We do NOT assume that it has type
1564 (>>=) :: m a -> (a -> m b) -> m b
1565 In some cases (see Trac #303, #1537) it might have a more
1566 exotic type, such as
1567 (>>=) :: m i j a -> (a -> m j k b) -> m i k b
1568 So we must be careful not to make assumptions about the type.
1569 In particular, the monad may not be uniform throughout.
1570
1571 Note [TransStmt binder map]
1572 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1573 The [(idR,idR)] in a TransStmt behaves as follows:
1574
1575 * Before renaming: []
1576
1577 * After renaming:
1578 [ (x27,x27), ..., (z35,z35) ]
1579 These are the variables
1580 bound by the stmts to the left of the 'group'
1581 and used either in the 'by' clause,
1582 or in the stmts following the 'group'
1583 Each item is a pair of identical variables.
1584
1585 * After typechecking:
1586 [ (x27:Int, x27:[Int]), ..., (z35:Bool, z35:[Bool]) ]
1587 Each pair has the same unique, but different *types*.
1588
1589 Note [BodyStmt]
1590 ~~~~~~~~~~~~~~~
1591 BodyStmts are a bit tricky, because what they mean
1592 depends on the context. Consider the following contexts:
1593
1594 A do expression of type (m res_ty)
1595 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1596 * BodyStmt E any_ty: do { ....; E; ... }
1597 E :: m any_ty
1598 Translation: E >> ...
1599
1600 A list comprehensions of type [elt_ty]
1601 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1602 * BodyStmt E Bool: [ .. | .... E ]
1603 [ .. | ..., E, ... ]
1604 [ .. | .... | ..., E | ... ]
1605 E :: Bool
1606 Translation: if E then fail else ...
1607
1608 A guard list, guarding a RHS of type rhs_ty
1609 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1610 * BodyStmt E BooParStmtBlockl: f x | ..., E, ... = ...rhs...
1611 E :: Bool
1612 Translation: if E then fail else ...
1613
1614 A monad comprehension of type (m res_ty)
1615 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1616 * BodyStmt E Bool: [ .. | .... E ]
1617 E :: Bool
1618 Translation: guard E >> ...
1619
1620 Array comprehensions are handled like list comprehensions.
1621
1622 Note [How RecStmt works]
1623 ~~~~~~~~~~~~~~~~~~~~~~~~
1624 Example:
1625 HsDo [ BindStmt x ex
1626
1627 , RecStmt { recS_rec_ids = [a, c]
1628 , recS_stmts = [ BindStmt b (return (a,c))
1629 , LetStmt a = ...b...
1630 , BindStmt c ec ]
1631 , recS_later_ids = [a, b]
1632
1633 , return (a b) ]
1634
1635 Here, the RecStmt binds a,b,c; but
1636 - Only a,b are used in the stmts *following* the RecStmt,
1637 - Only a,c are used in the stmts *inside* the RecStmt
1638 *before* their bindings
1639
1640 Why do we need *both* rec_ids and later_ids? For monads they could be
1641 combined into a single set of variables, but not for arrows. That
1642 follows from the types of the respective feedback operators:
1643
1644 mfix :: MonadFix m => (a -> m a) -> m a
1645 loop :: ArrowLoop a => a (b,d) (c,d) -> a b c
1646
1647 * For mfix, the 'a' covers the union of the later_ids and the rec_ids
1648 * For 'loop', 'c' is the later_ids and 'd' is the rec_ids
1649
1650 Note [Typing a RecStmt]
1651 ~~~~~~~~~~~~~~~~~~~~~~~
1652 A (RecStmt stmts) types as if you had written
1653
1654 (v1,..,vn, _, ..., _) <- mfix (\~(_, ..., _, r1, ..., rm) ->
1655 do { stmts
1656 ; return (v1,..vn, r1, ..., rm) })
1657
1658 where v1..vn are the later_ids
1659 r1..rm are the rec_ids
1660
1661 Note [Monad Comprehensions]
1662 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1663 Monad comprehensions require separate functions like 'return' and
1664 '>>=' for desugaring. These functions are stored in the statements
1665 used in monad comprehensions. For example, the 'return' of the 'LastStmt'
1666 expression is used to lift the body of the monad comprehension:
1667
1668 [ body | stmts ]
1669 =>
1670 stmts >>= \bndrs -> return body
1671
1672 In transform and grouping statements ('then ..' and 'then group ..') the
1673 'return' function is required for nested monad comprehensions, for example:
1674
1675 [ body | stmts, then f, rest ]
1676 =>
1677 f [ env | stmts ] >>= \bndrs -> [ body | rest ]
1678
1679 BodyStmts require the 'Control.Monad.guard' function for boolean
1680 expressions:
1681
1682 [ body | exp, stmts ]
1683 =>
1684 guard exp >> [ body | stmts ]
1685
1686 Parallel statements require the 'Control.Monad.Zip.mzip' function:
1687
1688 [ body | stmts1 | stmts2 | .. ]
1689 =>
1690 mzip stmts1 (mzip stmts2 (..)) >>= \(bndrs1, (bndrs2, ..)) -> return body
1691
1692 In any other context than 'MonadComp', the fields for most of these
1693 'SyntaxExpr's stay bottom.
1694 -}
1695
1696 instance (OutputableBndr idL)
1697 => Outputable (ParStmtBlock idL idR) where
1698 ppr (ParStmtBlock stmts _ _) = interpp'SP stmts
1699
1700 instance (OutputableBndr idL, OutputableBndr idR, Outputable body)
1701 => Outputable (StmtLR idL idR body) where
1702 ppr stmt = pprStmt stmt
1703
1704 pprStmt :: forall idL idR body . (OutputableBndr idL, OutputableBndr idR, Outputable body)
1705 => (StmtLR idL idR body) -> SDoc
1706 pprStmt (LastStmt expr ret_stripped _)
1707 = ifPprDebug (text "[last]") <+>
1708 (if ret_stripped then text "return" else empty) <+>
1709 ppr expr
1710 pprStmt (BindStmt pat expr _ _ _) = hsep [ppr pat, larrow, ppr expr]
1711 pprStmt (LetStmt (L _ binds)) = hsep [text "let", pprBinds binds]
1712 pprStmt (BodyStmt expr _ _ _) = ppr expr
1713 pprStmt (ParStmt stmtss _ _ _) = sep (punctuate (text " | ") (map ppr stmtss))
1714
1715 pprStmt (TransStmt { trS_stmts = stmts, trS_by = by, trS_using = using, trS_form = form })
1716 = sep $ punctuate comma (map ppr stmts ++ [pprTransStmt by using form])
1717
1718 pprStmt (RecStmt { recS_stmts = segment, recS_rec_ids = rec_ids
1719 , recS_later_ids = later_ids })
1720 = text "rec" <+>
1721 vcat [ ppr_do_stmts segment
1722 , ifPprDebug (vcat [ text "rec_ids=" <> ppr rec_ids
1723 , text "later_ids=" <> ppr later_ids])]
1724
1725 pprStmt (ApplicativeStmt args mb_join _)
1726 = getPprStyle $ \style ->
1727 if userStyle style
1728 then pp_for_user
1729 else pp_debug
1730 where
1731 -- make all the Applicative stuff invisible in error messages by
1732 -- flattening the whole ApplicativeStmt nest back to a sequence
1733 -- of statements.
1734 pp_for_user = vcat $ punctuate semi $ concatMap flattenArg args
1735
1736 -- ppr directly rather than transforming here, because we need to
1737 -- inject a "return" which is hard when we're polymorphic in the id
1738 -- type.
1739 flattenStmt :: ExprLStmt idL -> [SDoc]
1740 flattenStmt (L _ (ApplicativeStmt args _ _)) = concatMap flattenArg args
1741 flattenStmt stmt = [ppr stmt]
1742
1743 flattenArg (_, ApplicativeArgOne pat expr) =
1744 [ppr (BindStmt pat expr noSyntaxExpr noSyntaxExpr (panic "pprStmt")
1745 :: ExprStmt idL)]
1746 flattenArg (_, ApplicativeArgMany stmts _ _) =
1747 concatMap flattenStmt stmts
1748
1749 pp_debug =
1750 let
1751 ap_expr = sep (punctuate (text " |") (map pp_arg args))
1752 in
1753 if isNothing mb_join
1754 then ap_expr
1755 else text "join" <+> parens ap_expr
1756
1757 pp_arg (_, ApplicativeArgOne pat expr) =
1758 ppr (BindStmt pat expr noSyntaxExpr noSyntaxExpr (panic "pprStmt")
1759 :: ExprStmt idL)
1760 pp_arg (_, ApplicativeArgMany stmts return pat) =
1761 ppr pat <+>
1762 text "<-" <+>
1763 ppr (HsDo DoExpr (noLoc
1764 (stmts ++ [noLoc (LastStmt (noLoc return) False noSyntaxExpr)]))
1765 (error "pprStmt"))
1766
1767 pprTransformStmt :: OutputableBndr id => [id] -> LHsExpr id -> Maybe (LHsExpr id) -> SDoc
1768 pprTransformStmt bndrs using by
1769 = sep [ text "then" <+> ifPprDebug (braces (ppr bndrs))
1770 , nest 2 (ppr using)
1771 , nest 2 (pprBy by)]
1772
1773 pprTransStmt :: Outputable body => Maybe body -> body -> TransForm -> SDoc
1774 pprTransStmt by using ThenForm
1775 = sep [ text "then", nest 2 (ppr using), nest 2 (pprBy by)]
1776 pprTransStmt by using GroupForm
1777 = sep [ text "then group", nest 2 (pprBy by), nest 2 (ptext (sLit "using") <+> ppr using)]
1778
1779 pprBy :: Outputable body => Maybe body -> SDoc
1780 pprBy Nothing = empty
1781 pprBy (Just e) = text "by" <+> ppr e
1782
1783 pprDo :: (OutputableBndr id, Outputable body)
1784 => HsStmtContext any -> [LStmt id body] -> SDoc
1785 pprDo DoExpr stmts = text "do" <+> ppr_do_stmts stmts
1786 pprDo GhciStmtCtxt stmts = text "do" <+> ppr_do_stmts stmts
1787 pprDo ArrowExpr stmts = text "do" <+> ppr_do_stmts stmts
1788 pprDo MDoExpr stmts = text "mdo" <+> ppr_do_stmts stmts
1789 pprDo ListComp stmts = brackets $ pprComp stmts
1790 pprDo PArrComp stmts = paBrackets $ pprComp stmts
1791 pprDo MonadComp stmts = brackets $ pprComp stmts
1792 pprDo _ _ = panic "pprDo" -- PatGuard, ParStmtCxt
1793
1794 ppr_do_stmts :: (OutputableBndr idL, OutputableBndr idR, Outputable body)
1795 => [LStmtLR idL idR body] -> SDoc
1796 -- Print a bunch of do stmts, with explicit braces and semicolons,
1797 -- so that we are not vulnerable to layout bugs
1798 ppr_do_stmts stmts
1799 = lbrace <+> pprDeeperList vcat (punctuate semi (map ppr stmts))
1800 <+> rbrace
1801
1802 pprComp :: (OutputableBndr id, Outputable body)
1803 => [LStmt id body] -> SDoc
1804 pprComp quals -- Prints: body | qual1, ..., qualn
1805 | not (null quals)
1806 , L _ (LastStmt body _ _) <- last quals
1807 = hang (ppr body <+> vbar) 2 (pprQuals (dropTail 1 quals))
1808 | otherwise
1809 = pprPanic "pprComp" (pprQuals quals)
1810
1811 pprQuals :: (OutputableBndr id, Outputable body)
1812 => [LStmt id body] -> SDoc
1813 -- Show list comprehension qualifiers separated by commas
1814 pprQuals quals = interpp'SP quals
1815
1816 {-
1817 ************************************************************************
1818 * *
1819 Template Haskell quotation brackets
1820 * *
1821 ************************************************************************
1822 -}
1823
1824 data HsSplice id
1825 = HsTypedSplice -- $$z or $$(f 4)
1826 id -- A unique name to identify this splice point
1827 (LHsExpr id) -- See Note [Pending Splices]
1828
1829 | HsUntypedSplice -- $z or $(f 4)
1830 id -- A unique name to identify this splice point
1831 (LHsExpr id) -- See Note [Pending Splices]
1832
1833 | HsQuasiQuote -- See Note [Quasi-quote overview] in TcSplice
1834 id -- Splice point
1835 id -- Quoter
1836 SrcSpan -- The span of the enclosed string
1837 FastString -- The enclosed string
1838 deriving (Typeable )
1839
1840 deriving instance (DataId id) => Data (HsSplice id)
1841
1842 isTypedSplice :: HsSplice id -> Bool
1843 isTypedSplice (HsTypedSplice {}) = True
1844 isTypedSplice _ = False -- Quasi-quotes are untyped splices
1845
1846 -- See Note [Pending Splices]
1847 type SplicePointName = Name
1848
1849 data PendingRnSplice
1850 = PendingRnSplice UntypedSpliceFlavour SplicePointName (LHsExpr Name)
1851 deriving (Data, Typeable)
1852
1853 data UntypedSpliceFlavour
1854 = UntypedExpSplice
1855 | UntypedPatSplice
1856 | UntypedTypeSplice
1857 | UntypedDeclSplice
1858 deriving( Data, Typeable )
1859
1860 data PendingTcSplice
1861 = PendingTcSplice SplicePointName (LHsExpr Id)
1862 deriving( Data, Typeable )
1863
1864
1865 {-
1866 Note [Pending Splices]
1867 ~~~~~~~~~~~~~~~~~~~~~~
1868 When we rename an untyped bracket, we name and lift out all the nested
1869 splices, so that when the typechecker hits the bracket, it can
1870 typecheck those nested splices without having to walk over the untyped
1871 bracket code. So for example
1872 [| f $(g x) |]
1873 looks like
1874
1875 HsBracket (HsApp (HsVar "f") (HsSpliceE _ (g x)))
1876
1877 which the renamer rewrites to
1878
1879 HsRnBracketOut (HsApp (HsVar f) (HsSpliceE sn (g x)))
1880 [PendingRnSplice UntypedExpSplice sn (g x)]
1881
1882 * The 'sn' is the Name of the splice point, the SplicePointName
1883
1884 * The PendingRnExpSplice gives the splice that splice-point name maps to;
1885 and the typechecker can now conveniently find these sub-expressions
1886
1887 * The other copy of the splice, in the second argument of HsSpliceE
1888 in the renamed first arg of HsRnBracketOut
1889 is used only for pretty printing
1890
1891 There are four varieties of pending splices generated by the renamer,
1892 distinguished by their UntypedSpliceFlavour
1893
1894 * Pending expression splices (UntypedExpSplice), e.g.,
1895 [|$(f x) + 2|]
1896
1897 UntypedExpSplice is also used for
1898 * quasi-quotes, where the pending expression expands to
1899 $(quoter "...blah...")
1900 (see RnSplice.makePending, HsQuasiQuote case)
1901
1902 * cross-stage lifting, where the pending expression expands to
1903 $(lift x)
1904 (see RnSplice.checkCrossStageLifting)
1905
1906 * Pending pattern splices (UntypedPatSplice), e.g.,
1907 [| \$(f x) -> x |]
1908
1909 * Pending type splices (UntypedTypeSplice), e.g.,
1910 [| f :: $(g x) |]
1911
1912 * Pending declaration (UntypedDeclSplice), e.g.,
1913 [| let $(f x) in ... |]
1914
1915 There is a fifth variety of pending splice, which is generated by the type
1916 checker:
1917
1918 * Pending *typed* expression splices, (PendingTcSplice), e.g.,
1919 [||1 + $$(f 2)||]
1920
1921 It would be possible to eliminate HsRnBracketOut and use HsBracketOut for the
1922 output of the renamer. However, when pretty printing the output of the renamer,
1923 e.g., in a type error message, we *do not* want to print out the pending
1924 splices. In contrast, when pretty printing the output of the type checker, we
1925 *do* want to print the pending splices. So splitting them up seems to make
1926 sense, although I hate to add another constructor to HsExpr.
1927 -}
1928
1929 instance OutputableBndr id => Outputable (HsSplice id) where
1930 ppr s = pprSplice s
1931
1932 pprPendingSplice :: OutputableBndr id => SplicePointName -> LHsExpr id -> SDoc
1933 pprPendingSplice n e = angleBrackets (ppr n <> comma <+> ppr e)
1934
1935 pprSplice :: OutputableBndr id => HsSplice id -> SDoc
1936 pprSplice (HsTypedSplice n e) = ppr_splice (text "$$") n e
1937 pprSplice (HsUntypedSplice n e) = ppr_splice (text "$") n e
1938 pprSplice (HsQuasiQuote n q _ s) = ppr_quasi n q s
1939
1940 ppr_quasi :: OutputableBndr id => id -> id -> FastString -> SDoc
1941 ppr_quasi n quoter quote = ifPprDebug (brackets (ppr n)) <>
1942 char '[' <> ppr quoter <> vbar <>
1943 ppr quote <> text "|]"
1944
1945 ppr_splice :: OutputableBndr id => SDoc -> id -> LHsExpr id -> SDoc
1946 ppr_splice herald n e
1947 = herald <> ifPprDebug (brackets (ppr n)) <> eDoc
1948 where
1949 -- We use pprLExpr to match pprParendLExpr:
1950 -- Using pprLExpr makes sure that we go 'deeper'
1951 -- I think that is usually (always?) right
1952 pp_as_was = pprLExpr e
1953 eDoc = case unLoc e of
1954 HsPar _ -> pp_as_was
1955 HsVar _ -> pp_as_was
1956 _ -> parens pp_as_was
1957
1958 data HsBracket id = ExpBr (LHsExpr id) -- [| expr |]
1959 | PatBr (LPat id) -- [p| pat |]
1960 | DecBrL [LHsDecl id] -- [d| decls |]; result of parser
1961 | DecBrG (HsGroup id) -- [d| decls |]; result of renamer
1962 | TypBr (LHsType id) -- [t| type |]
1963 | VarBr Bool id -- True: 'x, False: ''T
1964 -- (The Bool flag is used only in pprHsBracket)
1965 | TExpBr (LHsExpr id) -- [|| expr ||]
1966 deriving (Typeable)
1967 deriving instance (DataId id) => Data (HsBracket id)
1968
1969 isTypedBracket :: HsBracket id -> Bool
1970 isTypedBracket (TExpBr {}) = True
1971 isTypedBracket _ = False
1972
1973 instance OutputableBndr id => Outputable (HsBracket id) where
1974 ppr = pprHsBracket
1975
1976
1977 pprHsBracket :: OutputableBndr id => HsBracket id -> SDoc
1978 pprHsBracket (ExpBr e) = thBrackets empty (ppr e)
1979 pprHsBracket (PatBr p) = thBrackets (char 'p') (ppr p)
1980 pprHsBracket (DecBrG gp) = thBrackets (char 'd') (ppr gp)
1981 pprHsBracket (DecBrL ds) = thBrackets (char 'd') (vcat (map ppr ds))
1982 pprHsBracket (TypBr t) = thBrackets (char 't') (ppr t)
1983 pprHsBracket (VarBr True n) = char '\'' <> ppr n
1984 pprHsBracket (VarBr False n) = text "''" <> ppr n
1985 pprHsBracket (TExpBr e) = thTyBrackets (ppr e)
1986
1987 thBrackets :: SDoc -> SDoc -> SDoc
1988 thBrackets pp_kind pp_body = char '[' <> pp_kind <> vbar <+>
1989 pp_body <+> text "|]"
1990
1991 thTyBrackets :: SDoc -> SDoc
1992 thTyBrackets pp_body = text "[||" <+> pp_body <+> ptext (sLit "||]")
1993
1994 instance Outputable PendingRnSplice where
1995 ppr (PendingRnSplice _ n e) = pprPendingSplice n e
1996
1997 instance Outputable PendingTcSplice where
1998 ppr (PendingTcSplice n e) = pprPendingSplice n e
1999
2000 {-
2001 ************************************************************************
2002 * *
2003 \subsection{Enumerations and list comprehensions}
2004 * *
2005 ************************************************************************
2006 -}
2007
2008 data ArithSeqInfo id
2009 = From (LHsExpr id)
2010 | FromThen (LHsExpr id)
2011 (LHsExpr id)
2012 | FromTo (LHsExpr id)
2013 (LHsExpr id)
2014 | FromThenTo (LHsExpr id)
2015 (LHsExpr id)
2016 (LHsExpr id)
2017 deriving (Typeable)
2018 deriving instance (DataId id) => Data (ArithSeqInfo id)
2019
2020 instance OutputableBndr id => Outputable (ArithSeqInfo id) where
2021 ppr (From e1) = hcat [ppr e1, pp_dotdot]
2022 ppr (FromThen e1 e2) = hcat [ppr e1, comma, space, ppr e2, pp_dotdot]
2023 ppr (FromTo e1 e3) = hcat [ppr e1, pp_dotdot, ppr e3]
2024 ppr (FromThenTo e1 e2 e3)
2025 = hcat [ppr e1, comma, space, ppr e2, pp_dotdot, ppr e3]
2026
2027 pp_dotdot :: SDoc
2028 pp_dotdot = text " .. "
2029
2030 {-
2031 ************************************************************************
2032 * *
2033 \subsection{HsMatchCtxt}
2034 * *
2035 ************************************************************************
2036 -}
2037
2038 data HsMatchContext id -- Context of a Match
2039 = FunRhs id -- Function binding for f
2040 | LambdaExpr -- Patterns of a lambda
2041 | CaseAlt -- Patterns and guards on a case alternative
2042 | IfAlt -- Guards of a multi-way if alternative
2043 | ProcExpr -- Patterns of a proc
2044 | PatBindRhs -- A pattern binding eg [y] <- e = e
2045
2046 | RecUpd -- Record update [used only in DsExpr to
2047 -- tell matchWrapper what sort of
2048 -- runtime error message to generate]
2049
2050 | StmtCtxt (HsStmtContext id) -- Pattern of a do-stmt, list comprehension,
2051 -- pattern guard, etc
2052
2053 | ThPatSplice -- A Template Haskell pattern splice
2054 | ThPatQuote -- A Template Haskell pattern quotation [p| (a,b) |]
2055 | PatSyn -- A pattern synonym declaration
2056 deriving (Data, Typeable)
2057
2058 data HsStmtContext id
2059 = ListComp
2060 | MonadComp
2061 | PArrComp -- Parallel array comprehension
2062
2063 | DoExpr -- do { ... }
2064 | MDoExpr -- mdo { ... } ie recursive do-expression
2065 | ArrowExpr -- do-notation in an arrow-command context
2066
2067 | GhciStmtCtxt -- A command-line Stmt in GHCi pat <- rhs
2068 | PatGuard (HsMatchContext id) -- Pattern guard for specified thing
2069 | ParStmtCtxt (HsStmtContext id) -- A branch of a parallel stmt
2070 | TransStmtCtxt (HsStmtContext id) -- A branch of a transform stmt
2071 deriving (Data, Typeable)
2072
2073 isListCompExpr :: HsStmtContext id -> Bool
2074 -- Uses syntax [ e | quals ]
2075 isListCompExpr ListComp = True
2076 isListCompExpr PArrComp = True
2077 isListCompExpr MonadComp = True
2078 isListCompExpr (ParStmtCtxt c) = isListCompExpr c
2079 isListCompExpr (TransStmtCtxt c) = isListCompExpr c
2080 isListCompExpr _ = False
2081
2082 isMonadCompExpr :: HsStmtContext id -> Bool
2083 isMonadCompExpr MonadComp = True
2084 isMonadCompExpr (ParStmtCtxt ctxt) = isMonadCompExpr ctxt
2085 isMonadCompExpr (TransStmtCtxt ctxt) = isMonadCompExpr ctxt
2086 isMonadCompExpr _ = False
2087
2088 matchSeparator :: HsMatchContext id -> SDoc
2089 matchSeparator (FunRhs {}) = text "="
2090 matchSeparator CaseAlt = text "->"
2091 matchSeparator IfAlt = text "->"
2092 matchSeparator LambdaExpr = text "->"
2093 matchSeparator ProcExpr = text "->"
2094 matchSeparator PatBindRhs = text "="
2095 matchSeparator (StmtCtxt _) = text "<-"
2096 matchSeparator RecUpd = panic "unused"
2097 matchSeparator ThPatSplice = panic "unused"
2098 matchSeparator ThPatQuote = panic "unused"
2099 matchSeparator PatSyn = panic "unused"
2100
2101 pprMatchContext :: Outputable id => HsMatchContext id -> SDoc
2102 pprMatchContext ctxt
2103 | want_an ctxt = text "an" <+> pprMatchContextNoun ctxt
2104 | otherwise = text "a" <+> pprMatchContextNoun ctxt
2105 where
2106 want_an (FunRhs {}) = True -- Use "an" in front
2107 want_an ProcExpr = True
2108 want_an _ = False
2109
2110 pprMatchContextNoun :: Outputable id => HsMatchContext id -> SDoc
2111 pprMatchContextNoun (FunRhs fun) = text "equation for"
2112 <+> quotes (ppr fun)
2113 pprMatchContextNoun CaseAlt = text "case alternative"
2114 pprMatchContextNoun IfAlt = text "multi-way if alternative"
2115 pprMatchContextNoun RecUpd = text "record-update construct"
2116 pprMatchContextNoun ThPatSplice = text "Template Haskell pattern splice"
2117 pprMatchContextNoun ThPatQuote = text "Template Haskell pattern quotation"
2118 pprMatchContextNoun PatBindRhs = text "pattern binding"
2119 pprMatchContextNoun LambdaExpr = text "lambda abstraction"
2120 pprMatchContextNoun ProcExpr = text "arrow abstraction"
2121 pprMatchContextNoun (StmtCtxt ctxt) = text "pattern binding in"
2122 $$ pprStmtContext ctxt
2123 pprMatchContextNoun PatSyn = text "pattern synonym declaration"
2124
2125 -----------------
2126 pprAStmtContext, pprStmtContext :: Outputable id => HsStmtContext id -> SDoc
2127 pprAStmtContext ctxt = article <+> pprStmtContext ctxt
2128 where
2129 pp_an = text "an"
2130 pp_a = text "a"
2131 article = case ctxt of
2132 MDoExpr -> pp_an
2133 PArrComp -> pp_an
2134 GhciStmtCtxt -> pp_an
2135 _ -> pp_a
2136
2137
2138 -----------------
2139 pprStmtContext GhciStmtCtxt = text "interactive GHCi command"
2140 pprStmtContext DoExpr = text "'do' block"
2141 pprStmtContext MDoExpr = text "'mdo' block"
2142 pprStmtContext ArrowExpr = text "'do' block in an arrow command"
2143 pprStmtContext ListComp = text "list comprehension"
2144 pprStmtContext MonadComp = text "monad comprehension"
2145 pprStmtContext PArrComp = text "array comprehension"
2146 pprStmtContext (PatGuard ctxt) = text "pattern guard for" $$ pprMatchContext ctxt
2147
2148 -- Drop the inner contexts when reporting errors, else we get
2149 -- Unexpected transform statement
2150 -- in a transformed branch of
2151 -- transformed branch of
2152 -- transformed branch of monad comprehension
2153 pprStmtContext (ParStmtCtxt c)
2154 | opt_PprStyle_Debug = sep [text "parallel branch of", pprAStmtContext c]
2155 | otherwise = pprStmtContext c
2156 pprStmtContext (TransStmtCtxt c)
2157 | opt_PprStyle_Debug = sep [text "transformed branch of", pprAStmtContext c]
2158 | otherwise = pprStmtContext c
2159
2160
2161 -- Used to generate the string for a *runtime* error message
2162 matchContextErrString :: Outputable id => HsMatchContext id -> SDoc
2163 matchContextErrString (FunRhs fun) = text "function" <+> ppr fun
2164 matchContextErrString CaseAlt = text "case"
2165 matchContextErrString IfAlt = text "multi-way if"
2166 matchContextErrString PatBindRhs = text "pattern binding"
2167 matchContextErrString RecUpd = text "record update"
2168 matchContextErrString LambdaExpr = text "lambda"
2169 matchContextErrString ProcExpr = text "proc"
2170 matchContextErrString ThPatSplice = panic "matchContextErrString" -- Not used at runtime
2171 matchContextErrString ThPatQuote = panic "matchContextErrString" -- Not used at runtime
2172 matchContextErrString PatSyn = panic "matchContextErrString" -- Not used at runtime
2173 matchContextErrString (StmtCtxt (ParStmtCtxt c)) = matchContextErrString (StmtCtxt c)
2174 matchContextErrString (StmtCtxt (TransStmtCtxt c)) = matchContextErrString (StmtCtxt c)
2175 matchContextErrString (StmtCtxt (PatGuard _)) = text "pattern guard"
2176 matchContextErrString (StmtCtxt GhciStmtCtxt) = text "interactive GHCi command"
2177 matchContextErrString (StmtCtxt DoExpr) = text "'do' block"
2178 matchContextErrString (StmtCtxt ArrowExpr) = text "'do' block"
2179 matchContextErrString (StmtCtxt MDoExpr) = text "'mdo' block"
2180 matchContextErrString (StmtCtxt ListComp) = text "list comprehension"
2181 matchContextErrString (StmtCtxt MonadComp) = text "monad comprehension"
2182 matchContextErrString (StmtCtxt PArrComp) = text "array comprehension"
2183
2184 pprMatchInCtxt :: (OutputableBndr idL, OutputableBndr idR, Outputable body)
2185 => HsMatchContext idL -> Match idR body -> SDoc
2186 pprMatchInCtxt ctxt match = hang (text "In" <+> pprMatchContext ctxt <> colon)
2187 4 (pprMatch ctxt match)
2188
2189 pprStmtInCtxt :: (OutputableBndr idL, OutputableBndr idR, Outputable body)
2190 => HsStmtContext idL -> StmtLR idL idR body -> SDoc
2191 pprStmtInCtxt ctxt (LastStmt e _ _)
2192 | isListCompExpr ctxt -- For [ e | .. ], do not mutter about "stmts"
2193 = hang (text "In the expression:") 2 (ppr e)
2194
2195 pprStmtInCtxt ctxt stmt
2196 = hang (text "In a stmt of" <+> pprAStmtContext ctxt <> colon)
2197 2 (ppr_stmt stmt)
2198 where
2199 -- For Group and Transform Stmts, don't print the nested stmts!
2200 ppr_stmt (TransStmt { trS_by = by, trS_using = using
2201 , trS_form = form }) = pprTransStmt by using form
2202 ppr_stmt stmt = pprStmt stmt