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