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