Initial checkin of HetMet / -XModalTypes modifications
[ghc-hetmet.git] / compiler / hsSyn / HsExpr.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5 \begin{code}
6 {-# LANGUAGE DeriveDataTypeable #-}
7
8 -- | Abstract Haskell syntax for expressions.
9 module HsExpr where
10
11 #include "HsVersions.h"
12
13 -- friends:
14 import HsDecls
15 import HsPat
16 import HsLit
17 import HsTypes
18 import HsBinds
19
20 -- others:
21 import Var
22 import Name
23 import BasicTypes
24 import DataCon
25 import SrcLoc
26 import Outputable
27 import FastString
28
29 -- libraries:
30 import Data.Data hiding (Fixity)
31 \end{code}
32
33
34 %************************************************************************
35 %*                                                                      *
36 \subsection{Expressions proper}
37 %*                                                                      *
38 %************************************************************************
39
40 \begin{code}
41 -- * Expressions proper
42
43 type LHsExpr id = Located (HsExpr id)
44
45 -------------------------
46 -- | PostTcExpr is an evidence expression attached to the syntax tree by the
47 -- type checker (c.f. postTcType).
48 type PostTcExpr  = HsExpr Id
49 -- | We use a PostTcTable where there are a bunch of pieces of evidence, more
50 -- than is convenient to keep individually.
51 type PostTcTable = [(Name, PostTcExpr)]
52
53 noPostTcExpr :: PostTcExpr
54 noPostTcExpr = HsLit (HsString (fsLit "noPostTcExpr"))
55
56 noPostTcTable :: PostTcTable
57 noPostTcTable = []
58
59 -------------------------
60 -- | SyntaxExpr is like 'PostTcExpr', but it's filled in a little earlier,
61 -- by the renamer.  It's used for rebindable syntax.
62 --
63 -- E.g. @(>>=)@ is filled in before the renamer by the appropriate 'Name' for
64 --      @(>>=)@, and then instantiated by the type checker with its type args
65 --      etc
66
67 type SyntaxExpr id = HsExpr id
68
69 noSyntaxExpr :: SyntaxExpr id -- Before renaming, and sometimes after,
70                               -- (if the syntax slot makes no sense)
71 noSyntaxExpr = HsLit (HsString (fsLit "noSyntaxExpr"))
72
73
74 type SyntaxTable id = [(Name, SyntaxExpr id)]
75 -- ^ Currently used only for 'CmdTop' (sigh)
76 --
77 -- * Before the renamer, this list is 'noSyntaxTable'
78 --
79 -- * After the renamer, it takes the form @[(std_name, HsVar actual_name)]@
80 --   For example, for the 'return' op of a monad
81 --
82 --    * normal case:            @(GHC.Base.return, HsVar GHC.Base.return)@
83 --
84 --    * with rebindable syntax: @(GHC.Base.return, return_22)@
85 --              where @return_22@ is whatever @return@ is in scope
86 --
87 -- * After the type checker, it takes the form @[(std_name, <expression>)]@
88 --      where @<expression>@ is the evidence for the method
89
90 noSyntaxTable :: SyntaxTable id
91 noSyntaxTable = []
92
93
94 -------------------------
95 -- | A Haskell expression.
96 data HsExpr id
97   = HsVar     id                        -- ^ variable
98   | HsIPVar   (IPName id)               -- ^ implicit parameter
99   | HsOverLit (HsOverLit id)            -- ^ Overloaded literals
100
101   | HsLit     HsLit                     -- ^ Simple (non-overloaded) literals
102
103   | HsLam     (MatchGroup id)           -- Currently always a single match
104
105   | HsApp     (LHsExpr id) (LHsExpr id) -- Application
106
107   -- Operator applications:
108   -- NB Bracketed ops such as (+) come out as Vars.
109
110   -- NB We need an expr for the operator in an OpApp/Section since
111   -- the typechecker may need to apply the operator to a few types.
112
113   | OpApp       (LHsExpr id)    -- left operand
114                 (LHsExpr id)    -- operator
115                 Fixity          -- Renamer adds fixity; bottom until then
116                 (LHsExpr id)    -- right operand
117
118   | NegApp      (LHsExpr id)    -- negated expr
119                 (SyntaxExpr id) -- Name of 'negate'
120
121   | HsPar       (LHsExpr id)    -- parenthesised expr
122
123   | SectionL    (LHsExpr id)    -- operand
124                 (LHsExpr id)    -- operator
125   | SectionR    (LHsExpr id)    -- operator
126                 (LHsExpr id)    -- operand
127
128   | ExplicitTuple               -- Used for explicit tuples and sections thereof
129         [HsTupArg id] 
130         Boxity
131
132   | HsCase      (LHsExpr id)
133                 (MatchGroup id)
134
135   | HsIf        (Maybe (SyntaxExpr id)) -- cond function
136                                         -- Nothing => use the built-in 'if'
137                                         -- See Note [Rebindable if]
138                 (LHsExpr id)    --  predicate
139                 (LHsExpr id)    --  then part
140                 (LHsExpr id)    --  else part
141
142   | HsLet       (HsLocalBinds id) -- let(rec)
143                 (LHsExpr  id)
144
145   | HsDo        (HsStmtContext Name) -- The parameterisation is unimportant
146                                      -- because in this context we never use
147                                      -- the PatGuard or ParStmt variant
148                 [LStmt id]           -- "do":one or more stmts
149                 (LHsExpr id)         -- The body; the last expression in the
150                                      -- 'do' of [ body | ... ] in a list comp
151                 PostTcType           -- Type of the whole expression
152
153   | ExplicitList                -- syntactic list
154                 PostTcType      -- Gives type of components of list
155                 [LHsExpr id]
156
157   | ExplicitPArr                -- syntactic parallel array: [:e1, ..., en:]
158                 PostTcType      -- type of elements of the parallel array
159                 [LHsExpr id]
160
161   -- Record construction
162   | RecordCon   (Located id)       -- The constructor.  After type checking
163                                    -- it's the dataConWrapId of the constructor
164                 PostTcExpr         -- Data con Id applied to type args
165                 (HsRecordBinds id)
166
167   -- Record update
168   | RecordUpd   (LHsExpr id)
169                 (HsRecordBinds id)
170 --              (HsMatchGroup Id)  -- Filled in by the type checker to be 
171 --                                 -- a match that does the job
172                 [DataCon]          -- Filled in by the type checker to the
173                                    -- _non-empty_ list of DataCons that have
174                                    -- all the upd'd fields
175                 [PostTcType]       -- Argument types of *input* record type
176                 [PostTcType]       --              and  *output* record type
177   -- For a type family, the arg types are of the *instance* tycon,
178   -- not the family tycon
179
180   | ExprWithTySig                       -- e :: type
181                 (LHsExpr id)
182                 (LHsType id)
183
184   | ExprWithTySigOut                    -- TRANSLATION
185                 (LHsExpr id)
186                 (LHsType Name)          -- Retain the signature for
187                                         -- round-tripping purposes
188
189   | ArithSeq                            -- arithmetic sequence
190                 PostTcExpr
191                 (ArithSeqInfo id)
192
193   | PArrSeq                             -- arith. sequence for parallel array
194                 PostTcExpr              -- [:e1..e2:] or [:e1, e2..e3:]
195                 (ArithSeqInfo id)
196
197   | HsSCC       FastString              -- "set cost centre" SCC pragma
198                 (LHsExpr id)            -- expr whose cost is to be measured
199
200   | HsCoreAnn   FastString              -- hdaume: core annotation
201                 (LHsExpr id)
202
203   -----------------------------------------------------------
204   -- MetaHaskell Extensions
205
206   | HsBracket    (HsBracket id)
207
208   | HsBracketOut (HsBracket Name)       -- Output of the type checker is
209                                         -- the *original*
210                  [PendingSplice]        -- renamed expression, plus
211                                         -- _typechecked_ splices to be
212                                         -- pasted back in by the desugarer
213
214   | HsSpliceE (HsSplice id)
215
216   | HsQuasiQuoteE (HsQuasiQuote id)
217         -- See Note [Quasi-quote overview] in TcSplice
218
219   -----------------------------------------------------------
220   -- Arrow notation extension
221
222   | HsProc      (LPat id)               -- arrow abstraction, proc
223                 (LHsCmdTop id)          -- body of the abstraction
224                                         -- always has an empty stack
225
226   -----------------------------------------------------------
227   -- Heterogeneous Metaprogramming extension
228
229   | HsHetMetBrak  PostTcType            (LHsExpr id)            -- code type brackets
230   | HsHetMetEsc   PostTcType PostTcType (LHsExpr id)            -- code type escape
231   | HsHetMetCSP   PostTcType            (LHsExpr id)            -- code type cross-stage persistence
232
233   ---------------------------------------
234   -- The following are commands, not expressions proper
235
236   | HsArrApp            -- Arrow tail, or arrow application (f -< arg)
237         (LHsExpr id)    -- arrow expression, f
238         (LHsExpr id)    -- input expression, arg
239         PostTcType      -- type of the arrow expressions f,
240                         -- of the form a t t', where arg :: t
241         HsArrAppType    -- higher-order (-<<) or first-order (-<)
242         Bool            -- True => right-to-left (f -< arg)
243                         -- False => left-to-right (arg >- f)
244
245   | HsArrForm           -- Command formation,  (| e cmd1 .. cmdn |)
246         (LHsExpr id)    -- the operator
247                         -- after type-checking, a type abstraction to be
248                         -- applied to the type of the local environment tuple
249         (Maybe Fixity)  -- fixity (filled in by the renamer), for forms that
250                         -- were converted from OpApp's by the renamer
251         [LHsCmdTop id]  -- argument commands
252
253
254   ---------------------------------------
255   -- Haskell program coverage (Hpc) Support
256
257   | HsTick
258      Int                                -- module-local tick number
259      [id]                               -- variables in scope
260      (LHsExpr id)                       -- sub-expression
261
262   | HsBinTick
263      Int                                -- module-local tick number for True
264      Int                                -- module-local tick number for False
265      (LHsExpr id)                       -- sub-expression
266
267   | HsTickPragma                        -- A pragma introduced tick
268      (FastString,(Int,Int),(Int,Int))   -- external span for this tick
269      (LHsExpr id)
270
271   ---------------------------------------
272   -- These constructors only appear temporarily in the parser.
273   -- The renamer translates them into the Right Thing.
274
275   | EWildPat                 -- wildcard
276
277   | EAsPat      (Located id) -- as pattern
278                 (LHsExpr id)
279
280   | EViewPat    (LHsExpr id) -- view pattern
281                 (LHsExpr id)
282
283   | ELazyPat    (LHsExpr id) -- ~ pattern
284
285   | HsType      (LHsType id) -- Explicit type argument; e.g  f {| Int |} x y
286
287   ---------------------------------------
288   -- Finally, HsWrap appears only in typechecker output
289
290   |  HsWrap     HsWrapper    -- TRANSLATION
291                 (HsExpr id)
292   deriving (Data, Typeable)
293
294 -- HsTupArg is used for tuple sections
295 --  (,a,) is represented by  ExplicitTuple [Mising ty1, Present a, Missing ty3]
296 --  Which in turn stands for (\x:ty1 \y:ty2. (x,a,y))
297 data HsTupArg id
298   = Present (LHsExpr id)        -- The argument
299   | Missing PostTcType          -- The argument is missing, but this is its type
300   deriving (Data, Typeable)
301
302 tupArgPresent :: HsTupArg id -> Bool
303 tupArgPresent (Present {}) = True
304 tupArgPresent (Missing {}) = False
305
306 type PendingSplice = (Name, LHsExpr Id) -- Typechecked splices, waiting to be
307                                         -- pasted back in by the desugarer
308 \end{code}
309
310 Note [Rebindable if]
311 ~~~~~~~~~~~~~~~~~~~~
312 The rebindable syntax for 'if' is a bit special, because when
313 rebindable syntax is *off* we do not want to treat
314    (if c then t else e)
315 as if it was an application (ifThenElse c t e).  Why not?
316 Because we allow an 'if' to return *unboxed* results, thus 
317   if blah then 3# else 4#
318 whereas that would not be possible using a all to a polymorphic function
319 (because you can't call a polymorphic function at an unboxed type).
320
321 So we use Nothing to mean "use the old built-in typing rule".
322
323 \begin{code}
324 instance OutputableBndr id => Outputable (HsExpr id) where
325     ppr expr = pprExpr expr
326 \end{code}
327
328 \begin{code}
329 -----------------------
330 -- pprExpr, pprLExpr, pprBinds call pprDeeper;
331 -- the underscore versions do not
332 pprLExpr :: OutputableBndr id => LHsExpr id -> SDoc
333 pprLExpr (L _ e) = pprExpr e
334
335 pprExpr :: OutputableBndr id => HsExpr id -> SDoc
336 pprExpr e | isAtomicHsExpr e || isQuietHsExpr e =            ppr_expr e
337           | otherwise                           = pprDeeper (ppr_expr e)
338
339 isQuietHsExpr :: HsExpr id -> Bool
340 -- Parentheses do display something, but it gives little info and
341 -- if we go deeper when we go inside them then we get ugly things
342 -- like (...)
343 isQuietHsExpr (HsPar _) = True
344 -- applications don't display anything themselves
345 isQuietHsExpr (HsApp _ _) = True
346 isQuietHsExpr (OpApp _ _ _ _) = True
347 isQuietHsExpr _ = False
348
349 pprBinds :: (OutputableBndr idL, OutputableBndr idR)
350          => HsLocalBindsLR idL idR -> SDoc
351 pprBinds b = pprDeeper (ppr b)
352
353 -----------------------
354 ppr_lexpr :: OutputableBndr id => LHsExpr id -> SDoc
355 ppr_lexpr e = ppr_expr (unLoc e)
356
357 ppr_expr :: OutputableBndr id => HsExpr id -> SDoc
358 ppr_expr (HsVar v)       = pprHsVar v
359 ppr_expr (HsIPVar v)     = ppr v
360 ppr_expr (HsLit lit)     = ppr lit
361 ppr_expr (HsOverLit lit) = ppr lit
362 ppr_expr (HsPar e)       = parens (ppr_lexpr e)
363 ppr_expr (HsHetMetBrak _   e) = ptext (sLit "<[") <> (ppr_lexpr e) <> ptext (sLit "]>")
364 ppr_expr (HsHetMetEsc  _ _ e) = ptext (sLit "~~") <> (ppr_lexpr e)
365 ppr_expr (HsHetMetCSP  _   e) = ptext (sLit "%%") <> (ppr_lexpr e)
366
367 ppr_expr (HsCoreAnn s e)
368   = vcat [ptext (sLit "HsCoreAnn") <+> ftext s, ppr_lexpr e]
369
370 ppr_expr (HsApp e1 e2)
371   = let (fun, args) = collect_args e1 [e2] in
372     hang (ppr_lexpr fun) 2 (sep (map pprParendExpr args))
373   where
374     collect_args (L _ (HsApp fun arg)) args = collect_args fun (arg:args)
375     collect_args fun args = (fun, args)
376
377 ppr_expr (OpApp e1 op _ e2)
378   = case unLoc op of
379       HsVar v -> pp_infixly v
380       _       -> pp_prefixly
381   where
382     pp_e1 = pprDebugParendExpr e1   -- In debug mode, add parens
383     pp_e2 = pprDebugParendExpr e2   -- to make precedence clear
384
385     pp_prefixly
386       = hang (ppr op) 2 (sep [pp_e1, pp_e2])
387
388     pp_infixly v
389       = sep [nest 2 pp_e1, pprHsInfix v, nest 2 pp_e2]
390
391 ppr_expr (NegApp e _) = char '-' <+> pprDebugParendExpr e
392
393 ppr_expr (SectionL expr op)
394   = case unLoc op of
395       HsVar v -> pp_infixly v
396       _       -> pp_prefixly
397   where
398     pp_expr = pprDebugParendExpr expr
399
400     pp_prefixly = hang (hsep [text " \\ x_ ->", ppr op])
401                        4 (hsep [pp_expr, ptext (sLit "x_ )")])
402     pp_infixly v = (sep [pp_expr, pprHsInfix v])
403
404 ppr_expr (SectionR op expr)
405   = case unLoc op of
406       HsVar v -> pp_infixly v
407       _       -> pp_prefixly
408   where
409     pp_expr = pprDebugParendExpr expr
410
411     pp_prefixly = hang (hsep [text "( \\ x_ ->", ppr op, ptext (sLit "x_")])
412                        4 ((<>) pp_expr rparen)
413     pp_infixly v
414       = (sep [pprHsInfix v, pp_expr])
415
416 ppr_expr (ExplicitTuple exprs boxity)
417   = tupleParens boxity (fcat (ppr_tup_args exprs))
418   where
419     ppr_tup_args []               = []
420     ppr_tup_args (Present e : es) = (ppr_lexpr e <> punc es) : ppr_tup_args es
421     ppr_tup_args (Missing _ : es) = punc es : ppr_tup_args es
422
423     punc (Present {} : _) = comma <> space
424     punc (Missing {} : _) = comma
425     punc []               = empty
426
427 --avoid using PatternSignatures for stage1 code portability
428 ppr_expr exprType@(HsLam matches)
429   = pprMatches (LambdaExpr `asTypeOf` idType exprType) matches
430  where idType :: HsExpr id -> HsMatchContext id; idType = undefined
431
432 ppr_expr exprType@(HsCase expr matches)
433   = sep [ sep [ptext (sLit "case"), nest 4 (ppr expr), ptext (sLit "of {")],
434           nest 2 (pprMatches (CaseAlt `asTypeOf` idType exprType) matches <+> char '}') ]
435  where idType :: HsExpr id -> HsMatchContext id; idType = undefined
436
437 ppr_expr (HsIf _ e1 e2 e3)
438   = sep [hsep [ptext (sLit "if"), nest 2 (ppr e1), ptext (sLit "then")],
439          nest 4 (ppr e2),
440          ptext (sLit "else"),
441          nest 4 (ppr e3)]
442
443 -- special case: let ... in let ...
444 ppr_expr (HsLet binds expr@(L _ (HsLet _ _)))
445   = sep [hang (ptext (sLit "let")) 2 (hsep [pprBinds binds, ptext (sLit "in")]),
446          ppr_lexpr expr]
447
448 ppr_expr (HsLet binds expr)
449   = sep [hang (ptext (sLit "let")) 2 (pprBinds binds),
450          hang (ptext (sLit "in"))  2 (ppr expr)]
451
452 ppr_expr (HsDo do_or_list_comp stmts body _) = pprDo do_or_list_comp stmts body
453
454 ppr_expr (ExplicitList _ exprs)
455   = brackets (pprDeeperList fsep (punctuate comma (map ppr_lexpr exprs)))
456
457 ppr_expr (ExplicitPArr _ exprs)
458   = pa_brackets (pprDeeperList fsep (punctuate comma (map ppr_lexpr exprs)))
459
460 ppr_expr (RecordCon con_id _ rbinds)
461   = hang (ppr con_id) 2 (ppr rbinds)
462
463 ppr_expr (RecordUpd aexp rbinds _ _ _)
464   = hang (pprParendExpr aexp) 2 (ppr rbinds)
465
466 ppr_expr (ExprWithTySig expr sig)
467   = hang (nest 2 (ppr_lexpr expr) <+> dcolon)
468          4 (ppr sig)
469 ppr_expr (ExprWithTySigOut expr sig)
470   = hang (nest 2 (ppr_lexpr expr) <+> dcolon)
471          4 (ppr sig)
472
473 ppr_expr (ArithSeq _ info) = brackets (ppr info)
474 ppr_expr (PArrSeq  _ info) = pa_brackets (ppr info)
475
476 ppr_expr EWildPat       = char '_'
477 ppr_expr (ELazyPat e)   = char '~' <> pprParendExpr e
478 ppr_expr (EAsPat v e)   = ppr v <> char '@' <> pprParendExpr e
479 ppr_expr (EViewPat p e) = ppr p <+> ptext (sLit "->") <+> ppr e
480
481 ppr_expr (HsSCC lbl expr)
482   = sep [ ptext (sLit "_scc_") <+> doubleQuotes (ftext lbl),
483           pprParendExpr expr ]
484
485 ppr_expr (HsWrap co_fn e) = pprHsWrapper (pprExpr e) co_fn
486 ppr_expr (HsType id)      = ppr id
487
488 ppr_expr (HsSpliceE s)       = pprSplice s
489 ppr_expr (HsBracket b)       = pprHsBracket b
490 ppr_expr (HsBracketOut e []) = ppr e
491 ppr_expr (HsBracketOut e ps) = ppr e $$ ptext (sLit "pending") <+> ppr ps
492 ppr_expr (HsQuasiQuoteE qq)  = ppr qq
493
494 ppr_expr (HsProc pat (L _ (HsCmdTop cmd _ _ _)))
495   = hsep [ptext (sLit "proc"), ppr pat, ptext (sLit "->"), ppr cmd]
496
497 ppr_expr (HsTick tickId vars exp)
498   = pprTicks (ppr exp) $
499     hcat [ptext (sLit "tick<"),
500     ppr tickId,
501     ptext (sLit ">("),
502     hsep (map pprHsVar vars),
503     ppr exp,
504     ptext (sLit ")")]
505 ppr_expr (HsBinTick tickIdTrue tickIdFalse exp)
506   = pprTicks (ppr exp) $
507     hcat [ptext (sLit "bintick<"),
508           ppr tickIdTrue,
509           ptext (sLit ","),
510           ppr tickIdFalse,
511           ptext (sLit ">("),
512           ppr exp,ptext (sLit ")")]
513 ppr_expr (HsTickPragma externalSrcLoc exp)
514   = pprTicks (ppr exp) $
515     hcat [ptext (sLit "tickpragma<"),
516           ppr externalSrcLoc,
517           ptext (sLit ">("),
518           ppr exp,
519           ptext (sLit ")")]
520
521 ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp True)
522   = hsep [ppr_lexpr arrow, ptext (sLit "-<"), ppr_lexpr arg]
523 ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp False)
524   = hsep [ppr_lexpr arg, ptext (sLit ">-"), ppr_lexpr arrow]
525 ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp True)
526   = hsep [ppr_lexpr arrow, ptext (sLit "-<<"), ppr_lexpr arg]
527 ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp False)
528   = hsep [ppr_lexpr arg, ptext (sLit ">>-"), ppr_lexpr arrow]
529
530 ppr_expr (HsArrForm (L _ (HsVar v)) (Just _) [arg1, arg2])
531   = sep [pprCmdArg (unLoc arg1), hsep [pprHsInfix v, pprCmdArg (unLoc arg2)]]
532 ppr_expr (HsArrForm op _ args)
533   = hang (ptext (sLit "(|") <> ppr_lexpr op)
534          4 (sep (map (pprCmdArg.unLoc) args) <> ptext (sLit "|)"))
535
536 pprCmdArg :: OutputableBndr id => HsCmdTop id -> SDoc
537 pprCmdArg (HsCmdTop cmd@(L _ (HsArrForm _ Nothing [])) _ _ _)
538   = ppr_lexpr cmd
539 pprCmdArg (HsCmdTop cmd _ _ _)
540   = parens (ppr_lexpr cmd)
541
542 instance OutputableBndr id => Outputable (HsCmdTop id) where
543     ppr = pprCmdArg
544
545 -- add parallel array brackets around a document
546 --
547 pa_brackets :: SDoc -> SDoc
548 pa_brackets p = ptext (sLit "[:") <> p <> ptext (sLit ":]")
549 \end{code}
550
551 HsSyn records exactly where the user put parens, with HsPar.
552 So generally speaking we print without adding any parens.
553 However, some code is internally generated, and in some places
554 parens are absolutely required; so for these places we use
555 pprParendExpr (but don't print double parens of course).
556
557 For operator applications we don't add parens, because the oprerator
558 fixities should do the job, except in debug mode (-dppr-debug) so we
559 can see the structure of the parse tree.
560
561 \begin{code}
562 pprDebugParendExpr :: OutputableBndr id => LHsExpr id -> SDoc
563 pprDebugParendExpr expr
564   = getPprStyle (\sty ->
565     if debugStyle sty then pprParendExpr expr
566                       else pprLExpr      expr)
567
568 pprParendExpr :: OutputableBndr id => LHsExpr id -> SDoc
569 pprParendExpr expr
570   = let
571         pp_as_was = pprLExpr expr
572         -- Using pprLExpr makes sure that we go 'deeper'
573         -- I think that is usually (always?) right
574     in
575     case unLoc expr of
576       ArithSeq {}       -> pp_as_was
577       PArrSeq {}        -> pp_as_was
578       HsLit {}          -> pp_as_was
579       HsOverLit {}      -> pp_as_was
580       HsVar {}          -> pp_as_was
581       HsIPVar {}        -> pp_as_was
582       ExplicitTuple {}  -> pp_as_was
583       ExplicitList {}   -> pp_as_was
584       ExplicitPArr {}   -> pp_as_was
585       HsPar {}          -> pp_as_was
586       HsBracket {}      -> pp_as_was
587       HsBracketOut _ [] -> pp_as_was
588       HsDo sc _ _ _
589        | isListCompExpr sc -> pp_as_was
590       _                    -> parens pp_as_was
591
592 isAtomicHsExpr :: HsExpr id -> Bool -- A single token
593 isAtomicHsExpr (HsVar {})     = True
594 isAtomicHsExpr (HsLit {})     = True
595 isAtomicHsExpr (HsOverLit {}) = True
596 isAtomicHsExpr (HsIPVar {})   = True
597 isAtomicHsExpr (HsWrap _ e)   = isAtomicHsExpr e
598 isAtomicHsExpr (HsPar e)      = isAtomicHsExpr (unLoc e)
599 isAtomicHsExpr _              = False
600 \end{code}
601
602 %************************************************************************
603 %*                                                                      *
604 \subsection{Commands (in arrow abstractions)}
605 %*                                                                      *
606 %************************************************************************
607
608 We re-use HsExpr to represent these.
609
610 \begin{code}
611 type HsCmd id = HsExpr id
612
613 type LHsCmd id = LHsExpr id
614
615 data HsArrAppType = HsHigherOrderApp | HsFirstOrderApp
616   deriving (Data, Typeable)
617 \end{code}
618
619 The legal constructors for commands are:
620
621   = HsArrApp ...                -- as above
622
623   | HsArrForm ...               -- as above
624
625   | HsApp       (HsCmd id)
626                 (HsExpr id)
627
628   | HsLam       (Match  id)     -- kappa
629
630   -- the renamer turns this one into HsArrForm
631   | OpApp       (HsExpr id)     -- left operand
632                 (HsCmd id)      -- operator
633                 Fixity          -- Renamer adds fixity; bottom until then
634                 (HsCmd id)      -- right operand
635
636   | HsPar       (HsCmd id)      -- parenthesised command
637
638   | HsCase      (HsExpr id)
639                 [Match id]      -- bodies are HsCmd's
640                 SrcLoc
641
642   | HsIf        (Maybe (SyntaxExpr id)) --  cond function
643                                          (HsExpr id)     --  predicate
644                 (HsCmd id)      --  then part
645                 (HsCmd id)      --  else part
646                 SrcLoc
647
648   | HsLet       (HsLocalBinds id)       -- let(rec)
649                 (HsCmd  id)
650
651   | HsDo        (HsStmtContext Name)    -- The parameterisation is unimportant
652                                         -- because in this context we never use
653                                         -- the PatGuard or ParStmt variant
654                 [Stmt id]       -- HsExpr's are really HsCmd's
655                 PostTcType      -- Type of the whole expression
656                 SrcLoc
657
658 Top-level command, introducing a new arrow.
659 This may occur inside a proc (where the stack is empty) or as an
660 argument of a command-forming operator.
661
662 \begin{code}
663 type LHsCmdTop id = Located (HsCmdTop id)
664
665 data HsCmdTop id
666   = HsCmdTop (LHsCmd id)
667              [PostTcType]     -- types of inputs on the command's stack
668              PostTcType       -- return type of the command
669              (SyntaxTable id) -- after type checking:
670                               -- names used in the command's desugaring
671   deriving (Data, Typeable)
672 \end{code}
673
674 %************************************************************************
675 %*                                                                      *
676 \subsection{Record binds}
677 %*                                                                      *
678 %************************************************************************
679
680 \begin{code}
681 type HsRecordBinds id = HsRecFields id (LHsExpr id)
682 \end{code}
683
684
685
686 %************************************************************************
687 %*                                                                      *
688 \subsection{@Match@, @GRHSs@, and @GRHS@ datatypes}
689 %*                                                                      *
690 %************************************************************************
691
692 @Match@es are sets of pattern bindings and right hand sides for
693 functions, patterns or case branches. For example, if a function @g@
694 is defined as:
695 \begin{verbatim}
696 g (x,y) = y
697 g ((x:ys),y) = y+1,
698 \end{verbatim}
699 then \tr{g} has two @Match@es: @(x,y) = y@ and @((x:ys),y) = y+1@.
700
701 It is always the case that each element of an @[Match]@ list has the
702 same number of @pats@s inside it.  This corresponds to saying that
703 a function defined by pattern matching must have the same number of
704 patterns in each equation.
705
706 \begin{code}
707 data MatchGroup id
708   = MatchGroup
709         [LMatch id]     -- The alternatives
710         PostTcType      -- The type is the type of the entire group
711                         --      t1 -> ... -> tn -> tr
712                         -- where there are n patterns
713   deriving (Data, Typeable)
714
715 type LMatch id = Located (Match id)
716
717 data Match id
718   = Match
719         [LPat id]               -- The patterns
720         (Maybe (LHsType id))    -- A type signature for the result of the match
721                                 -- Nothing after typechecking
722         (GRHSs id)
723   deriving (Data, Typeable)
724
725 isEmptyMatchGroup :: MatchGroup id -> Bool
726 isEmptyMatchGroup (MatchGroup ms _) = null ms
727
728 matchGroupArity :: MatchGroup id -> Arity
729 matchGroupArity (MatchGroup [] _)
730   = panic "matchGroupArity"     -- Precondition: MatchGroup is non-empty
731 matchGroupArity (MatchGroup (match:matches) _)
732   = ASSERT( all ((== n_pats) . length . hsLMatchPats) matches )
733     -- Assertion just checks that all the matches have the same number of pats
734     n_pats
735   where
736     n_pats = length (hsLMatchPats match)
737
738 hsLMatchPats :: LMatch id -> [LPat id]
739 hsLMatchPats (L _ (Match pats _ _)) = pats
740
741 -- | GRHSs are used both for pattern bindings and for Matches
742 data GRHSs id
743   = GRHSs {
744       grhssGRHSs :: [LGRHS id],  -- ^ Guarded RHSs
745       grhssLocalBinds :: (HsLocalBinds id) -- ^ The where clause
746     } deriving (Data, Typeable)
747
748 type LGRHS id = Located (GRHS id)
749
750 -- | Guarded Right Hand Side.
751 data GRHS id = GRHS [LStmt id]   -- Guards
752                     (LHsExpr id) -- Right hand side
753   deriving (Data, Typeable)
754 \end{code}
755
756 We know the list must have at least one @Match@ in it.
757
758 \begin{code}
759 pprMatches :: (OutputableBndr idL, OutputableBndr idR) => HsMatchContext idL -> MatchGroup idR -> SDoc
760 pprMatches ctxt (MatchGroup matches _)
761     = vcat (map (pprMatch ctxt) (map unLoc matches))
762       -- Don't print the type; it's only a place-holder before typechecking
763
764 -- Exported to HsBinds, which can't see the defn of HsMatchContext
765 pprFunBind :: (OutputableBndr idL, OutputableBndr idR) => idL -> Bool -> MatchGroup idR -> SDoc
766 pprFunBind fun inf matches = pprMatches (FunRhs fun inf) matches
767
768 -- Exported to HsBinds, which can't see the defn of HsMatchContext
769 pprPatBind :: (OutputableBndr bndr, OutputableBndr id)
770            => LPat bndr -> GRHSs id -> SDoc
771 pprPatBind pat ty@(grhss)
772  = sep [ppr pat, nest 2 (pprGRHSs (PatBindRhs `asTypeOf` idType ty) grhss)]
773 --avoid using PatternSignatures for stage1 code portability
774  where idType :: GRHSs id -> HsMatchContext id; idType = undefined
775
776
777 pprMatch :: (OutputableBndr idL, OutputableBndr idR) => HsMatchContext idL -> Match idR -> SDoc
778 pprMatch ctxt (Match pats maybe_ty grhss)
779   = sep [ sep (herald : map (nest 2 . pprParendLPat) other_pats)
780         , nest 2 ppr_maybe_ty
781         , nest 2 (pprGRHSs ctxt grhss) ]
782   where
783     (herald, other_pats)
784         = case ctxt of
785             FunRhs fun is_infix
786                 | not is_infix -> (ppr fun, pats)
787                         -- f x y z = e
788                         -- Not pprBndr; the AbsBinds will
789                         -- have printed the signature
790
791                 | null pats2 -> (pp_infix, [])
792                         -- x &&& y = e
793
794                 | otherwise -> (parens pp_infix, pats2)
795                         -- (x &&& y) z = e
796                 where
797                   pp_infix = pprParendLPat pat1 <+> ppr fun <+> pprParendLPat pat2
798
799             LambdaExpr -> (char '\\', pats)
800             
801             _  -> ASSERT( null pats1 )
802                   (ppr pat1, [])        -- No parens around the single pat
803
804     (pat1:pats1) = pats
805     (pat2:pats2) = pats1
806     ppr_maybe_ty = case maybe_ty of
807                         Just ty -> dcolon <+> ppr ty
808                         Nothing -> empty
809
810
811 pprGRHSs :: (OutputableBndr idL, OutputableBndr idR)
812          => HsMatchContext idL -> GRHSs idR -> SDoc
813 pprGRHSs ctxt (GRHSs grhss binds)
814   = vcat (map (pprGRHS ctxt . unLoc) grhss)
815  $$ ppUnless (isEmptyLocalBinds binds)
816       (text "where" $$ nest 4 (pprBinds binds))
817
818 pprGRHS :: (OutputableBndr idL, OutputableBndr idR)
819         => HsMatchContext idL -> GRHS idR -> SDoc
820
821 pprGRHS ctxt (GRHS [] expr)
822  =  pp_rhs ctxt expr
823
824 pprGRHS ctxt (GRHS guards expr)
825  = sep [char '|' <+> interpp'SP guards, pp_rhs ctxt expr]
826
827 pp_rhs :: OutputableBndr idR => HsMatchContext idL -> LHsExpr idR -> SDoc
828 pp_rhs ctxt rhs = matchSeparator ctxt <+> pprDeeper (ppr rhs)
829 \end{code}
830
831 %************************************************************************
832 %*                                                                      *
833 \subsection{Do stmts and list comprehensions}
834 %*                                                                      *
835 %************************************************************************
836
837 \begin{code}
838 type LStmt id = Located (StmtLR id id)
839 type LStmtLR idL idR = Located (StmtLR idL idR)
840
841 type Stmt id = StmtLR id id
842
843 -- The SyntaxExprs in here are used *only* for do-notation, which
844 -- has rebindable syntax.  Otherwise they are unused.
845 data StmtLR idL idR
846   = BindStmt (LPat idL)
847              (LHsExpr idR)
848              (SyntaxExpr idR) -- The (>>=) operator
849              (SyntaxExpr idR) -- The fail operator
850              -- The fail operator is noSyntaxExpr
851              -- if the pattern match can't fail
852
853   | ExprStmt (LHsExpr idR)     -- See Note [ExprStmt]
854              (SyntaxExpr idR) -- The (>>) operator
855              PostTcType       -- Element type of the RHS (used for arrows)
856
857   | LetStmt  (HsLocalBindsLR idL idR)
858
859   -- ParStmts only occur in a list comprehension
860   | ParStmt  [([LStmt idL], [idR])]
861   -- After renaming, the ids are the binders bound by the stmts and used
862   -- after them
863
864   -- "qs, then f by e" ==> TransformStmt qs binders f (Just e)
865   -- "qs, then f"      ==> TransformStmt qs binders f Nothing
866   | TransformStmt 
867          [LStmt idL]    -- Stmts are the ones to the left of the 'then'
868
869          [idR]          -- After renaming, the IDs are the binders occurring 
870                         -- within this transform statement that are used after it
871
872          (LHsExpr idR)          -- "then f"
873
874          (Maybe (LHsExpr idR))  -- "by e" (optional)
875
876   | GroupStmt 
877          [LStmt idL]      -- Stmts to the *left* of the 'group'
878                           -- which generates the tuples to be grouped
879
880          [(idR, idR)]     -- See Note [GroupStmt binder map]
881                                 
882          (Maybe (LHsExpr idR))  -- "by e" (optional)
883
884          (Either                -- "using f"
885              (LHsExpr idR)      --   Left f  => explicit "using f"
886              (SyntaxExpr idR))  --   Right f => implicit; filled in with 'groupWith'
887                                                         
888
889   -- Recursive statement (see Note [How RecStmt works] below)
890   | RecStmt
891      { recS_stmts :: [LStmtLR idL idR]
892
893         -- The next two fields are only valid after renaming
894      , recS_later_ids :: [idR] -- The ids are a subset of the variables bound by the
895                                -- stmts that are used in stmts that follow the RecStmt
896
897      , recS_rec_ids :: [idR]   -- Ditto, but these variables are the "recursive" ones,
898                                -- that are used before they are bound in the stmts of
899                                -- the RecStmt. 
900         -- An Id can be in both groups
901         -- Both sets of Ids are (now) treated monomorphically
902         -- See Note [How RecStmt works] for why they are separate
903
904         -- Rebindable syntax
905      , recS_bind_fn :: SyntaxExpr idR -- The bind function
906      , recS_ret_fn  :: SyntaxExpr idR -- The return function
907      , recS_mfix_fn :: SyntaxExpr idR -- The mfix function
908
909         -- These fields are only valid after typechecking
910      , recS_rec_rets :: [PostTcExpr] -- These expressions correspond 1-to-1 with
911                                      -- recS_rec_ids, and are the
912                                      -- expressions that should be returned by
913                                      -- the recursion.
914                                      -- They may not quite be the Ids themselves,
915                                      -- because the Id may be *polymorphic*, but
916                                      -- the returned thing has to be *monomorphic*, 
917                                      -- so they may be type applications
918       }
919   deriving (Data, Typeable)
920 \end{code}
921
922 Note [GroupStmt binder map]
923 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
924 The [(idR,idR)] in a GroupStmt behaves as follows:
925
926   * Before renaming: []
927
928   * After renaming: 
929           [ (x27,x27), ..., (z35,z35) ]
930     These are the variables 
931         bound by the stmts to the left of the 'group'
932        and used either in the 'by' clause, 
933                 or     in the stmts following the 'group'
934     Each item is a pair of identical variables.
935
936   * After typechecking: 
937           [ (x27:Int, x27:[Int]), ..., (z35:Bool, z35:[Bool]) ]
938     Each pair has the same unique, but different *types*.
939    
940 Note [ExprStmt]
941 ~~~~~~~~~~~~~~~
942 ExprStmts are a bit tricky, because what they mean
943 depends on the context.  Consider the following contexts:
944
945         A do expression of type (m res_ty)
946         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
947         * ExprStmt E any_ty:   do { ....; E; ... }
948                 E :: m any_ty
949           Translation: E >> ...
950
951         A list comprehensions of type [elt_ty]
952         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
953         * ExprStmt E Bool:   [ .. | .... E ]
954                         [ .. | ..., E, ... ]
955                         [ .. | .... | ..., E | ... ]
956                 E :: Bool
957           Translation: if E then fail else ...
958
959         A guard list, guarding a RHS of type rhs_ty
960         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
961         * ExprStmt E Bool:   f x | ..., E, ... = ...rhs...
962                 E :: Bool
963           Translation: if E then fail else ...
964
965 Array comprehensions are handled like list comprehensions -=chak
966
967 Note [How RecStmt works]
968 ~~~~~~~~~~~~~~~~~~~~~~~~
969 Example:
970    HsDo [ BindStmt x ex
971
972         , RecStmt { recS_rec_ids   = [a, c]
973                   , recS_stmts     = [ BindStmt b (return (a,c))
974                                      , LetStmt a = ...b...
975                                      , BindStmt c ec ]
976                   , recS_later_ids = [a, b]
977
978         , return (a b) ]
979
980 Here, the RecStmt binds a,b,c; but
981   - Only a,b are used in the stmts *following* the RecStmt,
982   - Only a,c are used in the stmts *inside* the RecStmt
983         *before* their bindings
984
985 Why do we need *both* rec_ids and later_ids?  For monads they could be
986 combined into a single set of variables, but not for arrows.  That
987 follows from the types of the respective feedback operators:
988
989         mfix :: MonadFix m => (a -> m a) -> m a
990         loop :: ArrowLoop a => a (b,d) (c,d) -> a b c
991
992 * For mfix, the 'a' covers the union of the later_ids and the rec_ids 
993 * For 'loop', 'c' is the later_ids and 'd' is the rec_ids 
994
995 Note [Typing a RecStmt]
996 ~~~~~~~~~~~~~~~~~~~~~~~
997 A (RecStmt stmts) types as if you had written
998
999   (v1,..,vn, _, ..., _) <- mfix (\~(_, ..., _, r1, ..., rm) ->
1000                                  do { stmts 
1001                                     ; return (v1,..vn, r1, ..., rm) })
1002
1003 where v1..vn are the later_ids
1004       r1..rm are the rec_ids
1005
1006
1007 \begin{code}
1008 instance (OutputableBndr idL, OutputableBndr idR) => Outputable (StmtLR idL idR) where
1009     ppr stmt = pprStmt stmt
1010
1011 pprStmt :: (OutputableBndr idL, OutputableBndr idR) => (StmtLR idL idR) -> SDoc
1012 pprStmt (BindStmt pat expr _ _)   = hsep [ppr pat, ptext (sLit "<-"), ppr expr]
1013 pprStmt (LetStmt binds)           = hsep [ptext (sLit "let"), pprBinds binds]
1014 pprStmt (ExprStmt expr _ _)       = ppr expr
1015 pprStmt (ParStmt stmtss)          = hsep (map doStmts stmtss)
1016   where doStmts stmts = ptext (sLit "| ") <> ppr stmts
1017
1018 pprStmt (TransformStmt stmts bndrs using by)
1019   = sep (ppr_lc_stmts stmts ++ [pprTransformStmt bndrs using by])
1020
1021 pprStmt (GroupStmt stmts _ by using) 
1022   = sep (ppr_lc_stmts stmts ++ [pprGroupStmt by using])
1023
1024 pprStmt (RecStmt { recS_stmts = segment, recS_rec_ids = rec_ids
1025                  , recS_later_ids = later_ids })
1026   = ptext (sLit "rec") <+> 
1027     vcat [ braces (vcat (map ppr segment))
1028          , ifPprDebug (vcat [ ptext (sLit "rec_ids=") <> ppr rec_ids
1029                             , ptext (sLit "later_ids=") <> ppr later_ids])]
1030
1031 pprTransformStmt :: OutputableBndr id => [id] -> LHsExpr id -> Maybe (LHsExpr id) -> SDoc
1032 pprTransformStmt bndrs using by
1033   = sep [ ptext (sLit "then") <+> ifPprDebug (braces (ppr bndrs))
1034         , nest 2 (ppr using)
1035         , nest 2 (pprBy by)]
1036
1037 pprGroupStmt :: OutputableBndr id => Maybe (LHsExpr id)
1038                                   -> Either (LHsExpr id) (SyntaxExpr is)
1039                                   -> SDoc
1040 pprGroupStmt by using 
1041   = sep [ ptext (sLit "then group"), nest 2 (pprBy by), nest 2 (ppr_using using)]
1042   where
1043     ppr_using (Right _) = empty
1044     ppr_using (Left e)  = ptext (sLit "using") <+> ppr e
1045
1046 pprBy :: OutputableBndr id => Maybe (LHsExpr id) -> SDoc
1047 pprBy Nothing  = empty
1048 pprBy (Just e) = ptext (sLit "by") <+> ppr e
1049
1050 pprDo :: OutputableBndr id => HsStmtContext any -> [LStmt id] -> LHsExpr id -> SDoc
1051 pprDo DoExpr      stmts body = ptext (sLit "do")  <+> ppr_do_stmts stmts body
1052 pprDo GhciStmt    stmts body = ptext (sLit "do")  <+> ppr_do_stmts stmts body
1053 pprDo MDoExpr     stmts body = ptext (sLit "mdo") <+> ppr_do_stmts stmts body
1054 pprDo ListComp    stmts body = brackets    $ pprComp stmts body
1055 pprDo PArrComp    stmts body = pa_brackets $ pprComp stmts body
1056 pprDo _           _     _    = panic "pprDo" -- PatGuard, ParStmtCxt
1057
1058 ppr_do_stmts :: OutputableBndr id => [LStmt id] -> LHsExpr id -> SDoc
1059 -- Print a bunch of do stmts, with explicit braces and semicolons,
1060 -- so that we are not vulnerable to layout bugs
1061 ppr_do_stmts stmts body
1062   = lbrace <+> pprDeeperList vcat ([ppr s <> semi | s <- stmts] ++ [ppr body])
1063            <+> rbrace
1064
1065 ppr_lc_stmts :: OutputableBndr id => [LStmt id] -> [SDoc]
1066 ppr_lc_stmts stmts = [ppr s <> comma | s <- stmts]
1067
1068 pprComp :: OutputableBndr id => [LStmt id] -> LHsExpr id -> SDoc
1069 pprComp quals body        -- Prints:  body | qual1, ..., qualn 
1070   = hang (ppr body <+> char '|') 2 (interpp'SP quals)
1071 \end{code}
1072
1073 %************************************************************************
1074 %*                                                                      *
1075                 Template Haskell quotation brackets
1076 %*                                                                      *
1077 %************************************************************************
1078
1079 \begin{code}
1080 data HsSplice id  = HsSplice            --  $z  or $(f 4)
1081                         id              -- The id is just a unique name to
1082                         (LHsExpr id)    -- identify this splice point
1083   deriving (Data, Typeable)
1084
1085 instance OutputableBndr id => Outputable (HsSplice id) where
1086   ppr = pprSplice
1087
1088 pprSplice :: OutputableBndr id => HsSplice id -> SDoc
1089 pprSplice (HsSplice n e)
1090     = char '$' <> ifPprDebug (brackets (ppr n)) <> eDoc
1091     where
1092           -- We use pprLExpr to match pprParendExpr:
1093           --     Using pprLExpr makes sure that we go 'deeper'
1094           --     I think that is usually (always?) right
1095           pp_as_was = pprLExpr e
1096           eDoc = case unLoc e of
1097                  HsPar _ -> pp_as_was
1098                  HsVar _ -> pp_as_was
1099                  _ -> parens pp_as_was
1100
1101 data HsBracket id = ExpBr (LHsExpr id)   -- [|  expr  |]
1102                   | PatBr (LPat id)      -- [p| pat   |]
1103                   | DecBrL [LHsDecl id]  -- [d| decls |]; result of parser
1104                   | DecBrG (HsGroup id)  -- [d| decls |]; result of renamer
1105                   | TypBr (LHsType id)   -- [t| type  |]
1106                   | VarBr id             -- 'x, ''T
1107   deriving (Data, Typeable)
1108
1109 instance OutputableBndr id => Outputable (HsBracket id) where
1110   ppr = pprHsBracket
1111
1112
1113 pprHsBracket :: OutputableBndr id => HsBracket id -> SDoc
1114 pprHsBracket (ExpBr e)   = thBrackets empty (ppr e)
1115 pprHsBracket (PatBr p)   = thBrackets (char 'p') (ppr p)
1116 pprHsBracket (DecBrG gp) = thBrackets (char 'd') (ppr gp)
1117 pprHsBracket (DecBrL ds) = thBrackets (char 'd') (vcat (map ppr ds))
1118 pprHsBracket (TypBr t)   = thBrackets (char 't') (ppr t)
1119 pprHsBracket (VarBr n)   = char '\'' <> ppr n
1120 -- Infelicity: can't show ' vs '', because
1121 -- we can't ask n what its OccName is, because the
1122 -- pretty-printer for HsExpr doesn't ask for NamedThings
1123 -- But the pretty-printer for names will show the OccName class
1124
1125 thBrackets :: SDoc -> SDoc -> SDoc
1126 thBrackets pp_kind pp_body = char '[' <> pp_kind <> char '|' <+>
1127                              pp_body <+> ptext (sLit "|]")
1128 \end{code}
1129
1130 %************************************************************************
1131 %*                                                                      *
1132 \subsection{Enumerations and list comprehensions}
1133 %*                                                                      *
1134 %************************************************************************
1135
1136 \begin{code}
1137 data ArithSeqInfo id
1138   = From            (LHsExpr id)
1139   | FromThen        (LHsExpr id)
1140                     (LHsExpr id)
1141   | FromTo          (LHsExpr id)
1142                     (LHsExpr id)
1143   | FromThenTo      (LHsExpr id)
1144                     (LHsExpr id)
1145                     (LHsExpr id)
1146   deriving (Data, Typeable)
1147 \end{code}
1148
1149 \begin{code}
1150 instance OutputableBndr id => Outputable (ArithSeqInfo id) where
1151     ppr (From e1)             = hcat [ppr e1, pp_dotdot]
1152     ppr (FromThen e1 e2)      = hcat [ppr e1, comma, space, ppr e2, pp_dotdot]
1153     ppr (FromTo e1 e3)        = hcat [ppr e1, pp_dotdot, ppr e3]
1154     ppr (FromThenTo e1 e2 e3)
1155       = hcat [ppr e1, comma, space, ppr e2, pp_dotdot, ppr e3]
1156
1157 pp_dotdot :: SDoc
1158 pp_dotdot = ptext (sLit " .. ")
1159 \end{code}
1160
1161
1162 %************************************************************************
1163 %*                                                                      *
1164 \subsection{HsMatchCtxt}
1165 %*                                                                      *
1166 %************************************************************************
1167
1168 \begin{code}
1169 data HsMatchContext id  -- Context of a Match
1170   = FunRhs id Bool              -- Function binding for f; True <=> written infix
1171   | LambdaExpr                  -- Patterns of a lambda
1172   | CaseAlt                     -- Patterns and guards on a case alternative
1173   | ProcExpr                    -- Patterns of a proc
1174   | PatBindRhs                  -- A pattern binding  eg [y] <- e = e
1175
1176   | RecUpd                      -- Record update [used only in DsExpr to
1177                                 --    tell matchWrapper what sort of
1178                                 --    runtime error message to generate]
1179
1180   | StmtCtxt (HsStmtContext id) -- Pattern of a do-stmt, list comprehension, 
1181                                 -- pattern guard, etc
1182
1183   | ThPatQuote                  -- A Template Haskell pattern quotation [p| (a,b) |]
1184   deriving (Data, Typeable)
1185
1186 data HsStmtContext id
1187   = ListComp
1188   | DoExpr
1189   | GhciStmt                             -- A command-line Stmt in GHCi pat <- rhs
1190   | MDoExpr                              -- Recursive do-expression
1191   | PArrComp                             -- Parallel array comprehension
1192   | PatGuard (HsMatchContext id)         -- Pattern guard for specified thing
1193   | ParStmtCtxt (HsStmtContext id)       -- A branch of a parallel stmt
1194   | TransformStmtCtxt (HsStmtContext id) -- A branch of a transform stmt
1195   deriving (Data, Typeable)
1196 \end{code}
1197
1198 \begin{code}
1199 isDoExpr :: HsStmtContext id -> Bool
1200 isDoExpr DoExpr  = True
1201 isDoExpr MDoExpr = True
1202 isDoExpr _       = False
1203
1204 isListCompExpr :: HsStmtContext id -> Bool
1205 isListCompExpr ListComp = True
1206 isListCompExpr PArrComp = True
1207 isListCompExpr _        = False
1208 \end{code}
1209
1210 \begin{code}
1211 matchSeparator :: HsMatchContext id -> SDoc
1212 matchSeparator (FunRhs {})  = ptext (sLit "=")
1213 matchSeparator CaseAlt      = ptext (sLit "->")
1214 matchSeparator LambdaExpr   = ptext (sLit "->")
1215 matchSeparator ProcExpr     = ptext (sLit "->")
1216 matchSeparator PatBindRhs   = ptext (sLit "=")
1217 matchSeparator (StmtCtxt _) = ptext (sLit "<-")
1218 matchSeparator RecUpd       = panic "unused"
1219 matchSeparator ThPatQuote   = panic "unused"
1220 \end{code}
1221
1222 \begin{code}
1223 pprMatchContext :: Outputable id => HsMatchContext id -> SDoc
1224 pprMatchContext ctxt 
1225   | want_an ctxt = ptext (sLit "an") <+> pprMatchContextNoun ctxt
1226   | otherwise    = ptext (sLit "a")  <+> pprMatchContextNoun ctxt
1227   where
1228     want_an (FunRhs {}) = True  -- Use "an" in front
1229     want_an ProcExpr    = True
1230     want_an _           = False
1231                  
1232 pprMatchContextNoun :: Outputable id => HsMatchContext id -> SDoc
1233 pprMatchContextNoun (FunRhs fun _)  = ptext (sLit "equation for")
1234                                       <+> quotes (ppr fun)
1235 pprMatchContextNoun CaseAlt         = ptext (sLit "case alternative")
1236 pprMatchContextNoun RecUpd          = ptext (sLit "record-update construct")
1237 pprMatchContextNoun ThPatQuote      = ptext (sLit "Template Haskell pattern quotation")
1238 pprMatchContextNoun PatBindRhs      = ptext (sLit "pattern binding")
1239 pprMatchContextNoun LambdaExpr      = ptext (sLit "lambda abstraction")
1240 pprMatchContextNoun ProcExpr        = ptext (sLit "arrow abstraction")
1241 pprMatchContextNoun (StmtCtxt ctxt) = ptext (sLit "pattern binding in")
1242                                       $$ pprStmtContext ctxt
1243
1244 pprStmtContext :: Outputable id => HsStmtContext id -> SDoc
1245 pprStmtContext (ParStmtCtxt c)
1246  = sep [ptext (sLit "a parallel branch of"), pprStmtContext c]
1247 pprStmtContext (TransformStmtCtxt c)
1248  = sep [ptext (sLit "a transformed branch of"), pprStmtContext c]
1249 pprStmtContext (PatGuard ctxt)
1250  = ptext (sLit "a pattern guard for") $$ pprMatchContext ctxt
1251 pprStmtContext GhciStmt        = ptext (sLit "an interactive GHCi command")
1252 pprStmtContext DoExpr          = ptext (sLit "a 'do' expression")
1253 pprStmtContext MDoExpr         = ptext (sLit "an 'mdo' expression")
1254 pprStmtContext ListComp        = ptext (sLit "a list comprehension")
1255 pprStmtContext PArrComp        = ptext (sLit "an array comprehension")
1256
1257 {-
1258 pprMatchRhsContext (FunRhs fun) = ptext (sLit "a right-hand side of function") <+> quotes (ppr fun)
1259 pprMatchRhsContext CaseAlt      = ptext (sLit "the body of a case alternative")
1260 pprMatchRhsContext PatBindRhs   = ptext (sLit "the right-hand side of a pattern binding")
1261 pprMatchRhsContext LambdaExpr   = ptext (sLit "the body of a lambda")
1262 pprMatchRhsContext ProcExpr     = ptext (sLit "the body of a proc")
1263 pprMatchRhsContext other        = panic "pprMatchRhsContext"    -- RecUpd, StmtCtxt
1264
1265 -- Used for the result statement of comprehension
1266 -- e.g. the 'e' in      [ e | ... ]
1267 --      or the 'r' in   f x = r
1268 pprStmtResultContext (PatGuard ctxt) = pprMatchRhsContext ctxt
1269 pprStmtResultContext other           = ptext (sLit "the result of") <+> pprStmtContext other
1270 -}
1271
1272 -- Used to generate the string for a *runtime* error message
1273 matchContextErrString :: Outputable id => HsMatchContext id -> SDoc
1274 matchContextErrString (FunRhs fun _)             = ptext (sLit "function") <+> ppr fun
1275 matchContextErrString CaseAlt                    = ptext (sLit "case")
1276 matchContextErrString PatBindRhs                 = ptext (sLit "pattern binding")
1277 matchContextErrString RecUpd                     = ptext (sLit "record update")
1278 matchContextErrString LambdaExpr                 = ptext (sLit "lambda")
1279 matchContextErrString ProcExpr                   = ptext (sLit "proc")
1280 matchContextErrString ThPatQuote                 = panic "matchContextErrString"  -- Not used at runtime
1281 matchContextErrString (StmtCtxt (ParStmtCtxt c)) = matchContextErrString (StmtCtxt c)
1282 matchContextErrString (StmtCtxt (TransformStmtCtxt c)) = matchContextErrString (StmtCtxt c)
1283 matchContextErrString (StmtCtxt (PatGuard _))    = ptext (sLit "pattern guard")
1284 matchContextErrString (StmtCtxt GhciStmt)        = ptext (sLit "interactive GHCi command")
1285 matchContextErrString (StmtCtxt DoExpr)          = ptext (sLit "'do' expression")
1286 matchContextErrString (StmtCtxt MDoExpr)         = ptext (sLit "'mdo' expression")
1287 matchContextErrString (StmtCtxt ListComp)        = ptext (sLit "list comprehension")
1288 matchContextErrString (StmtCtxt PArrComp)        = ptext (sLit "array comprehension")
1289 \end{code}
1290
1291 \begin{code}
1292 pprMatchInCtxt :: (OutputableBndr idL, OutputableBndr idR)
1293                => HsMatchContext idL -> Match idR -> SDoc
1294 pprMatchInCtxt ctxt match  = hang (ptext (sLit "In") <+> pprMatchContext ctxt <> colon) 
1295                              4 (pprMatch ctxt match)
1296
1297 pprStmtInCtxt :: (OutputableBndr idL, OutputableBndr idR)
1298                => HsStmtContext idL -> StmtLR idL idR -> SDoc
1299 pprStmtInCtxt ctxt stmt = hang (ptext (sLit "In a stmt of") <+> pprStmtContext ctxt <> colon)
1300                           4 (ppr_stmt stmt)
1301   where
1302     -- For Group and Transform Stmts, don't print the nested stmts!
1303     ppr_stmt (GroupStmt _ _ by using)         = pprGroupStmt by using
1304     ppr_stmt (TransformStmt _ bndrs using by) = pprTransformStmt bndrs using by
1305     ppr_stmt stmt                             = pprStmt stmt
1306 \end{code}