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