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