fa817757857004ef19082cb7fd96056623d3333d
[ghc-hetmet.git] / ghc / compiler / hsSyn / HsExpr.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[HsExpr]{Abstract Haskell syntax: expressions}
5
6 \begin{code}
7 module HsExpr where
8
9 #include "HsVersions.h"
10
11 -- friends:
12 import HsBinds          ( HsBinds(..), nullBinds )
13 import HsTypes          ( PostTcType )
14 import HsLit            ( HsLit, HsOverLit )
15 import BasicTypes       ( Fixity(..) )
16 import HsTypes          ( HsType )
17 import HsImpExp         ( isOperator )
18
19 -- others:
20 import Name             ( Name )
21 import ForeignCall      ( Safety )
22 import Outputable       
23 import PprType          ( pprParendType )
24 import Type             ( Type  )
25 import Var              ( TyVar )
26 import DataCon          ( DataCon )
27 import CStrings         ( CLabelString, pprCLabelString )
28 import BasicTypes       ( IPName, Boxity, tupleParens )
29 import SrcLoc           ( SrcLoc )
30 import FastString
31 \end{code}
32
33 %************************************************************************
34 %*                                                                      *
35 \subsection{Expressions proper}
36 %*                                                                      *
37 %************************************************************************
38
39 \begin{code}
40 data HsExpr id pat
41   = HsVar       id              -- variable
42   | HsIPVar     (IPName id)     -- implicit parameter
43   | HsOverLit   HsOverLit       -- Overloaded literals; eliminated by type checker
44   | HsLit       HsLit           -- Simple (non-overloaded) literals
45
46   | HsLam       (Match  id pat) -- lambda
47   | HsApp       (HsExpr id pat) -- application
48                 (HsExpr id pat)
49
50   -- Operator applications:
51   -- NB Bracketed ops such as (+) come out as Vars.
52
53   -- NB We need an expr for the operator in an OpApp/Section since
54   -- the typechecker may need to apply the operator to a few types.
55
56   | OpApp       (HsExpr id pat) -- left operand
57                 (HsExpr id pat) -- operator
58                 Fixity                          -- Renamer adds fixity; bottom until then
59                 (HsExpr id pat) -- right operand
60
61   -- We preserve prefix negation and parenthesis for the precedence parser.
62   -- They are eventually removed by the type checker.
63
64   | NegApp      (HsExpr id pat) -- negated expr
65                 Name            -- Name of 'negate' (see RnEnv.lookupSyntaxName)
66
67   | HsPar       (HsExpr id pat) -- parenthesised expr
68
69   | SectionL    (HsExpr id pat) -- operand
70                 (HsExpr id pat) -- operator
71   | SectionR    (HsExpr id pat) -- operator
72                 (HsExpr id pat) -- operand
73                                 
74   | HsCase      (HsExpr id pat)
75                 [Match id pat]
76                 SrcLoc
77
78   | HsIf        (HsExpr id pat) --  predicate
79                 (HsExpr id pat) --  then part
80                 (HsExpr id pat) --  else part
81                 SrcLoc
82
83   | HsLet       (HsBinds id pat)        -- let(rec)
84                 (HsExpr  id pat)
85
86   | HsWith      (HsExpr id pat) -- implicit parameter binding
87                 [(IPName id, HsExpr id pat)]
88                 Bool            -- True <=> this was a 'with' binding
89                                 --  (tmp, until 'with' is removed)
90
91   | HsDo        HsDoContext
92                 [Stmt id pat]   -- "do":one or more stmts
93                 SrcLoc
94
95   | HsDoOut     HsDoContext
96                 [Stmt id pat]   -- "do":one or more stmts
97                 [id]            -- ids for [return,fail,>>=,>>]
98                                 --      Brutal but simple
99                 Type            -- Type of the whole expression
100                 SrcLoc
101
102   | ExplicitList                -- syntactic list
103                 PostTcType      -- Gives type of components of list
104                 [HsExpr id pat]
105
106   | ExplicitPArr                -- syntactic parallel array: [:e1, ..., en:]
107                 PostTcType      -- type of elements of the parallel array
108                 [HsExpr id pat]
109
110   | ExplicitTuple               -- tuple
111                 [HsExpr id pat]
112                                 -- NB: Unit is ExplicitTuple []
113                                 -- for tuples, we can get the types
114                                 -- direct from the components
115                 Boxity
116
117
118         -- Record construction
119   | RecordCon   id                              -- The constructor
120                 (HsRecordBinds id pat)
121
122   | RecordConOut DataCon
123                 (HsExpr id pat)         -- Data con Id applied to type args
124                 (HsRecordBinds id pat)
125
126
127         -- Record update
128   | RecordUpd   (HsExpr id pat)
129                 (HsRecordBinds id pat)
130
131   | RecordUpdOut (HsExpr id pat)        -- TRANSLATION
132                  Type                   -- Type of *input* record
133                  Type                   -- Type of *result* record (may differ from
134                                         --      type of input record)
135                  (HsRecordBinds id pat)
136
137   | ExprWithTySig                       -- signature binding
138                 (HsExpr id pat)
139                 (HsType id)
140   | ArithSeqIn                          -- arithmetic sequence
141                 (ArithSeqInfo id pat)
142   | ArithSeqOut
143                 (HsExpr id pat)         -- (typechecked, of course)
144                 (ArithSeqInfo id pat)
145   | PArrSeqIn                           -- arith. sequence for parallel array
146                 (ArithSeqInfo id pat)   -- [:e1..e2:] or [:e1, e2..e3:]
147   | PArrSeqOut
148                 (HsExpr id pat)         -- (typechecked, of course)
149                 (ArithSeqInfo id pat)
150
151   | HsCCall     CLabelString    -- call into the C world; string is
152                 [HsExpr id pat] -- the C function; exprs are the
153                                 -- arguments to pass.
154                 Safety          -- True <=> might cause Haskell
155                                 -- garbage-collection (must generate
156                                 -- more paranoid code)
157                 Bool            -- True <=> it's really a "casm"
158                                 -- NOTE: this CCall is the *boxed*
159                                 -- version; the desugarer will convert
160                                 -- it into the unboxed "ccall#".
161                 PostTcType      -- The result type; will be *bottom*
162                                 -- until the typechecker gets ahold of it
163
164   | HsSCC       FastString      -- "set cost centre" (_scc_) annotation
165                 (HsExpr id pat) -- expr whose cost is to be measured
166
167 \end{code}
168
169 These constructors only appear temporarily in the parser.
170 The renamer translates them into the Right Thing.
171
172 \begin{code}
173   | EWildPat                    -- wildcard
174
175   | EAsPat      id              -- as pattern
176                 (HsExpr id pat)
177
178   | ELazyPat    (HsExpr id pat) -- ~ pattern
179
180   | HsType      (HsType id)     -- Explicit type argument; e.g  f {| Int |} x y
181 \end{code}
182
183 Everything from here on appears only in typechecker output.
184
185 \begin{code}
186   | TyLam                       -- TRANSLATION
187                 [TyVar]
188                 (HsExpr id pat)
189   | TyApp                       -- TRANSLATION
190                 (HsExpr id pat) -- generated by Spec
191                 [Type]
192
193   -- DictLam and DictApp are "inverses"
194   |  DictLam
195                 [id]
196                 (HsExpr id pat)
197   |  DictApp
198                 (HsExpr id pat)
199                 [id]
200
201 type HsRecordBinds id pat
202   = [(id, HsExpr id pat, Bool)]
203         -- True <=> source code used "punning",
204         -- i.e. {op1, op2} rather than {op1=e1, op2=e2}
205 \end{code}
206
207 A @Dictionary@, unless of length 0 or 1, becomes a tuple.  A
208 @ClassDictLam dictvars methods expr@ is, therefore:
209 \begin{verbatim}
210 \ x -> case x of ( dictvars-and-methods-tuple ) -> expr
211 \end{verbatim}
212
213 \begin{code}
214 instance (Outputable id, Outputable pat) =>
215                 Outputable (HsExpr id pat) where
216     ppr expr = pprExpr expr
217 \end{code}
218
219 \begin{code}
220 pprExpr :: (Outputable id, Outputable pat)
221         => HsExpr id pat -> SDoc
222
223 pprExpr e = pprDeeper (ppr_expr e)
224 pprBinds b = pprDeeper (ppr b)
225
226 ppr_expr (HsVar v) 
227         -- Put it in parens if it's an operator
228   | isOperator v = parens (ppr v)
229   | otherwise    = ppr v
230
231 ppr_expr (HsIPVar v)     = ppr v
232 ppr_expr (HsLit lit)     = ppr lit
233 ppr_expr (HsOverLit lit) = ppr lit
234
235 ppr_expr (HsLam match)
236   = hsep [char '\\', nest 2 (pprMatch LambdaExpr match)]
237
238 ppr_expr expr@(HsApp e1 e2)
239   = let (fun, args) = collect_args expr [] in
240     (ppr_expr fun) <+> (sep (map ppr_expr args))
241   where
242     collect_args (HsApp fun arg) args = collect_args fun (arg:args)
243     collect_args fun             args = (fun, args)
244
245 ppr_expr (OpApp e1 op fixity e2)
246   = case op of
247       HsVar v -> pp_infixly v
248       _       -> pp_prefixly
249   where
250     pp_e1 = pprParendExpr e1            -- Add parens to make precedence clear
251     pp_e2 = pprParendExpr e2
252
253     pp_prefixly
254       = hang (pprExpr op) 4 (sep [pp_e1, pp_e2])
255
256     pp_infixly v
257       = sep [pp_e1, hsep [pp_v_op, pp_e2]]
258       where
259         pp_v_op | isOperator v = ppr v
260                 | otherwise    = char '`' <> ppr v <> char '`'
261                 -- Put it in backquotes if it's not an operator already
262
263 ppr_expr (NegApp e _) = char '-' <+> pprParendExpr e
264
265 ppr_expr (HsPar e) = parens (ppr_expr e)
266
267 ppr_expr (SectionL expr op)
268   = case op of
269       HsVar v -> pp_infixly v
270       _       -> pp_prefixly
271   where
272     pp_expr = pprParendExpr expr
273
274     pp_prefixly = hang (hsep [text " \\ x_ ->", ppr op])
275                        4 (hsep [pp_expr, ptext SLIT("x_ )")])
276     pp_infixly v = parens (sep [pp_expr, ppr v])
277
278 ppr_expr (SectionR op expr)
279   = case op of
280       HsVar v -> pp_infixly v
281       _       -> pp_prefixly
282   where
283     pp_expr = pprParendExpr expr
284
285     pp_prefixly = hang (hsep [text "( \\ x_ ->", ppr op, ptext SLIT("x_")])
286                        4 ((<>) pp_expr rparen)
287     pp_infixly v
288       = parens (sep [ppr v, pp_expr])
289
290 ppr_expr (HsCase expr matches _)
291   = sep [ sep [ptext SLIT("case"), nest 4 (pprExpr expr), ptext SLIT("of")],
292             nest 2 (pprMatches CaseAlt matches) ]
293
294 ppr_expr (HsIf e1 e2 e3 _)
295   = sep [hsep [ptext SLIT("if"), nest 2 (pprExpr e1), ptext SLIT("then")],
296            nest 4 (pprExpr e2),
297            ptext SLIT("else"),
298            nest 4 (pprExpr e3)]
299
300 -- special case: let ... in let ...
301 ppr_expr (HsLet binds expr@(HsLet _ _))
302   = sep [hang (ptext SLIT("let")) 2 (hsep [pprBinds binds, ptext SLIT("in")]),
303          pprExpr expr]
304
305 ppr_expr (HsLet binds expr)
306   = sep [hang (ptext SLIT("let")) 2 (pprBinds binds),
307          hang (ptext SLIT("in"))  2 (ppr expr)]
308
309 ppr_expr (HsWith expr binds is_with)
310   = sep [hang (ptext SLIT("let")) 2 (pp_ipbinds binds),
311          hang (ptext SLIT("in"))  2 (ppr expr)]
312
313 ppr_expr (HsDo do_or_list_comp stmts _)        = pprDo do_or_list_comp stmts
314 ppr_expr (HsDoOut do_or_list_comp stmts _ _ _) = pprDo do_or_list_comp stmts
315
316 ppr_expr (ExplicitList _ exprs)
317   = brackets (fsep (punctuate comma (map ppr_expr exprs)))
318
319 ppr_expr (ExplicitPArr _ exprs)
320   = pabrackets (fsep (punctuate comma (map ppr_expr exprs)))
321
322 ppr_expr (ExplicitTuple exprs boxity)
323   = tupleParens boxity (sep (punctuate comma (map ppr_expr exprs)))
324
325 ppr_expr (RecordCon con_id rbinds)
326   = pp_rbinds (ppr con_id) rbinds
327 ppr_expr (RecordConOut data_con con rbinds)
328   = pp_rbinds (ppr con) rbinds
329
330 ppr_expr (RecordUpd aexp rbinds)
331   = pp_rbinds (pprParendExpr aexp) rbinds
332 ppr_expr (RecordUpdOut aexp _ _ rbinds)
333   = pp_rbinds (pprParendExpr aexp) rbinds
334
335 ppr_expr (ExprWithTySig expr sig)
336   = hang (nest 2 (ppr_expr expr) <+> dcolon)
337          4 (ppr sig)
338
339 ppr_expr (ArithSeqIn info)
340   = brackets (ppr info)
341 ppr_expr (ArithSeqOut expr info)
342   = brackets (ppr info)
343
344 ppr_expr (PArrSeqIn info)
345   = pabrackets (ppr info)
346 ppr_expr (PArrSeqOut expr info)
347   = pabrackets (ppr info)
348
349 ppr_expr EWildPat = char '_'
350 ppr_expr (ELazyPat e) = char '~' <> pprParendExpr e
351 ppr_expr (EAsPat v e) = ppr v <> char '@' <> pprParendExpr e
352
353 ppr_expr (HsCCall fun args _ is_asm result_ty)
354   = hang (if is_asm
355           then ptext SLIT("_casm_ ``") <> pprCLabelString fun <> ptext SLIT("''")
356           else ptext SLIT("_ccall_") <+> pprCLabelString fun)
357        4 (sep (map pprParendExpr args))
358
359 ppr_expr (HsSCC lbl expr)
360   = sep [ ptext SLIT("_scc_") <+> doubleQuotes (ftext lbl), pprParendExpr expr ]
361
362 ppr_expr (TyLam tyvars expr)
363   = hang (hsep [ptext SLIT("/\\"), interppSP tyvars, ptext SLIT("->")])
364          4 (ppr_expr expr)
365
366 ppr_expr (TyApp expr [ty])
367   = hang (ppr_expr expr) 4 (pprParendType ty)
368
369 ppr_expr (TyApp expr tys)
370   = hang (ppr_expr expr)
371          4 (brackets (interpp'SP tys))
372
373 ppr_expr (DictLam dictvars expr)
374   = hang (hsep [ptext SLIT("\\{-dict-}"), interppSP dictvars, ptext SLIT("->")])
375          4 (ppr_expr expr)
376
377 ppr_expr (DictApp expr [dname])
378   = hang (ppr_expr expr) 4 (ppr dname)
379
380 ppr_expr (DictApp expr dnames)
381   = hang (ppr_expr expr)
382          4 (brackets (interpp'SP dnames))
383
384 ppr_expr (HsType id) = ppr id
385
386 -- add parallel array brackets around a document
387 --
388 pabrackets   :: SDoc -> SDoc
389 pabrackets p  = ptext SLIT("[:") <> p <> ptext SLIT(":]")    
390 \end{code}
391
392 Parenthesize unless very simple:
393 \begin{code}
394 pprParendExpr :: (Outputable id, Outputable pat)
395               => HsExpr id pat -> SDoc
396
397 pprParendExpr expr
398   = let
399         pp_as_was = pprExpr expr
400     in
401     case expr of
402       HsLit l               -> ppr l
403       HsOverLit l           -> ppr l
404
405       HsVar _               -> pp_as_was
406       HsIPVar _             -> pp_as_was
407       ExplicitList _ _      -> pp_as_was
408       ExplicitPArr _ _      -> pp_as_was
409       ExplicitTuple _ _     -> pp_as_was
410       HsPar _               -> pp_as_was
411
412       _                     -> parens pp_as_was
413 \end{code}
414
415 %************************************************************************
416 %*                                                                      *
417 \subsection{Record binds}
418 %*                                                                      *
419 %************************************************************************
420
421 \begin{code}
422 pp_rbinds :: (Outputable id, Outputable pat)
423               => SDoc 
424               -> HsRecordBinds id pat -> SDoc
425
426 pp_rbinds thing rbinds
427   = hang thing 
428          4 (braces (sep (punctuate comma (map (pp_rbind) rbinds))))
429   where
430     pp_rbind (v, e, pun_flag) 
431       = getPprStyle $ \ sty ->
432         if pun_flag && userStyle sty then
433            ppr v
434         else
435            hsep [ppr v, char '=', ppr e]
436 \end{code}
437
438 \begin{code}
439 pp_ipbinds :: (Outputable id, Outputable pat)
440            => [(IPName id, HsExpr id pat)] -> SDoc
441 pp_ipbinds pairs = hsep (punctuate semi (map pp_item pairs))
442                  where
443                    pp_item (id,rhs) = ppr id <+> equals <+> ppr_expr rhs
444 \end{code}
445
446
447 %************************************************************************
448 %*                                                                      *
449 \subsection{@Match@, @GRHSs@, and @GRHS@ datatypes}
450 %*                                                                      *
451 %************************************************************************
452
453 @Match@es are sets of pattern bindings and right hand sides for
454 functions, patterns or case branches. For example, if a function @g@
455 is defined as:
456 \begin{verbatim}
457 g (x,y) = y
458 g ((x:ys),y) = y+1,
459 \end{verbatim}
460 then \tr{g} has two @Match@es: @(x,y) = y@ and @((x:ys),y) = y+1@.
461
462 It is always the case that each element of an @[Match]@ list has the
463 same number of @pats@s inside it.  This corresponds to saying that
464 a function defined by pattern matching must have the same number of
465 patterns in each equation.
466
467 \begin{code}
468 data Match id pat
469   = Match
470         [pat]                   -- The patterns
471         (Maybe (HsType id))     -- A type signature for the result of the match
472                                 --      Nothing after typechecking
473
474         (GRHSs id pat)
475
476 -- GRHSs are used both for pattern bindings and for Matches
477 data GRHSs id pat       
478   = GRHSs [GRHS id pat]         -- Guarded RHSs
479           (HsBinds id pat)      -- The where clause
480           PostTcType            -- Type of RHS (after type checking)
481
482 data GRHS id pat
483   = GRHS  [Stmt id pat]         -- The RHS is the final ResultStmt
484                                 -- I considered using a RetunStmt, but
485                                 -- it printed 'wrong' in error messages 
486           SrcLoc
487
488 mkSimpleMatch :: [pat] -> HsExpr id pat -> Type -> SrcLoc -> Match id pat
489 mkSimpleMatch pats rhs rhs_ty locn
490   = Match pats Nothing (GRHSs (unguardedRHS rhs locn) EmptyBinds rhs_ty)
491
492 unguardedRHS :: HsExpr id pat -> SrcLoc -> [GRHS id pat]
493 unguardedRHS rhs loc = [GRHS [ResultStmt rhs loc] loc]
494 \end{code}
495
496 @getMatchLoc@ takes a @Match@ and returns the
497 source-location gotten from the GRHS inside.
498 THis is something of a nuisance, but no more.
499
500 \begin{code}
501 getMatchLoc :: Match id pat -> SrcLoc
502 getMatchLoc (Match _ _ (GRHSs (GRHS _ loc : _) _ _)) = loc
503 \end{code}
504
505 We know the list must have at least one @Match@ in it.
506
507 \begin{code}
508 pprMatches :: (Outputable id, Outputable pat)
509            => HsMatchContext id -> [Match id pat] -> SDoc
510 pprMatches ctxt matches = vcat (map (pprMatch ctxt) matches)
511
512 -- Exported to HsBinds, which can't see the defn of HsMatchContext
513 pprFunBind :: (Outputable id, Outputable pat)
514            => id -> [Match id pat] -> SDoc
515 pprFunBind fun matches = pprMatches (FunRhs fun) matches
516
517 -- Exported to HsBinds, which can't see the defn of HsMatchContext
518 pprPatBind :: (Outputable id, Outputable pat)
519            => pat -> GRHSs id pat -> SDoc
520 pprPatBind pat grhss = sep [ppr pat, nest 4 (pprGRHSs PatBindRhs grhss)]
521
522
523 pprMatch :: (Outputable id, Outputable pat)
524            => HsMatchContext id -> Match id pat -> SDoc
525 pprMatch ctxt (Match pats maybe_ty grhss)
526   = pp_name ctxt <+> sep [sep (map ppr pats), 
527                      ppr_maybe_ty,
528                      nest 2 (pprGRHSs ctxt grhss)]
529   where
530     pp_name (FunRhs fun) = ppr fun
531     pp_name other        = empty
532     ppr_maybe_ty = case maybe_ty of
533                         Just ty -> dcolon <+> ppr ty
534                         Nothing -> empty
535
536
537 pprGRHSs :: (Outputable id, Outputable pat)
538          => HsMatchContext id -> GRHSs id pat -> SDoc
539 pprGRHSs ctxt (GRHSs grhss binds ty)
540   = vcat (map (pprGRHS ctxt) grhss)
541     $$
542     (if nullBinds binds then empty
543      else text "where" $$ nest 4 (pprDeeper (ppr binds)))
544
545
546 pprGRHS :: (Outputable id, Outputable pat)
547         => HsMatchContext id -> GRHS id pat -> SDoc
548
549 pprGRHS ctxt (GRHS [ResultStmt expr _] locn)
550  =  pp_rhs ctxt expr
551
552 pprGRHS ctxt (GRHS guarded locn)
553  = sep [char '|' <+> interpp'SP guards, pp_rhs ctxt expr]
554  where
555     ResultStmt expr _ = last guarded    -- Last stmt should be a ResultStmt for guards
556     guards            = init guarded
557
558 pp_rhs ctxt rhs = matchSeparator ctxt <+> pprDeeper (ppr rhs)
559 \end{code}
560
561
562
563 %************************************************************************
564 %*                                                                      *
565 \subsection{Do stmts and list comprehensions}
566 %*                                                                      *
567 %************************************************************************
568
569 \begin{code}
570 data Stmt id pat
571   = BindStmt    pat (HsExpr id pat) SrcLoc
572   | LetStmt     (HsBinds id pat)
573   | ResultStmt  (HsExpr id pat) SrcLoc                  -- See notes that follow
574   | ExprStmt    (HsExpr id pat) PostTcType SrcLoc       -- See notes that follow
575         -- The type is the *element type* of the expression
576   | ParStmt     [[Stmt id pat]]                         -- List comp only: parallel set of quals
577   | ParStmtOut  [([id], [Stmt id pat])]                 -- PLC after renaming; the ids are the binders
578                                                         -- bound by the stmts
579 \end{code}
580
581 ExprStmts and ResultStmts are a bit tricky, because what they mean
582 depends on the context.  Consider the following contexts:
583
584         A do expression of type (m res_ty)
585         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
586         * ExprStmt E any_ty:   do { ....; E; ... }
587                 E :: m any_ty
588           Translation: E >> ...
589         
590         * ResultStmt E:   do { ....; E }
591                 E :: m res_ty
592           Translation: E
593         
594         A list comprehensions of type [elt_ty]
595         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
596         * ExprStmt E Bool:   [ .. | .... E ]
597                         [ .. | ..., E, ... ]
598                         [ .. | .... | ..., E | ... ]
599                 E :: Bool
600           Translation: if E then fail else ...
601
602         * ResultStmt E:   [ E | ... ]
603                 E :: elt_ty
604           Translation: return E
605         
606         A guard list, guarding a RHS of type rhs_ty
607         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
608         * ExprStmt E Bool:   f x | ..., E, ... = ...rhs...
609                 E :: Bool
610           Translation: if E then fail else ...
611         
612         * ResultStmt E:   f x | ...guards... = E
613                 E :: rhs_ty
614           Translation: E
615
616 Array comprehensions are handled like list comprehensions -=chak
617
618 \begin{code}
619 consLetStmt :: HsBinds id pat -> [Stmt id pat] -> [Stmt id pat]
620 consLetStmt EmptyBinds stmts = stmts
621 consLetStmt binds      stmts = LetStmt binds : stmts
622 \end{code}
623
624 \begin{code}
625 instance (Outputable id, Outputable pat) =>
626                 Outputable (Stmt id pat) where
627     ppr stmt = pprStmt stmt
628
629 pprStmt (BindStmt pat expr _) = hsep [ppr pat, ptext SLIT("<-"), ppr expr]
630 pprStmt (LetStmt binds)       = hsep [ptext SLIT("let"), pprBinds binds]
631 pprStmt (ExprStmt expr _ _)   = ppr expr
632 pprStmt (ResultStmt expr _)   = ppr expr
633 pprStmt (ParStmt stmtss)
634  = hsep (map (\stmts -> ptext SLIT("| ") <> ppr stmts) stmtss)
635 pprStmt (ParStmtOut stmtss)
636  = hsep (map (\stmts -> ptext SLIT("| ") <> ppr stmts) stmtss)
637
638 pprDo :: (Outputable id, Outputable pat) 
639       => HsDoContext -> [Stmt id pat] -> SDoc
640 pprDo DoExpr stmts   = hang (ptext SLIT("do")) 2 (vcat (map ppr stmts))
641 pprDo ListComp stmts = pprComp brackets   stmts
642 pprDo PArrComp stmts = pprComp pabrackets stmts
643
644 pprComp :: (Outputable id, Outputable pat) 
645         => (SDoc -> SDoc) -> [Stmt id pat] -> SDoc
646 pprComp brack stmts = brack $
647                       hang (pprExpr expr <+> char '|')
648                          4 (interpp'SP quals)
649                     where
650                       ResultStmt expr _ = last stmts  -- Last stmt should
651                       quals             = init stmts  -- be an ResultStmt
652 \end{code}
653
654 %************************************************************************
655 %*                                                                      *
656 \subsection{Enumerations and list comprehensions}
657 %*                                                                      *
658 %************************************************************************
659
660 \begin{code}
661 data ArithSeqInfo id pat
662   = From            (HsExpr id pat)
663   | FromThen        (HsExpr id pat)
664                     (HsExpr id pat)
665   | FromTo          (HsExpr id pat)
666                     (HsExpr id pat)
667   | FromThenTo      (HsExpr id pat)
668                     (HsExpr id pat)
669                     (HsExpr id pat)
670 \end{code}
671
672 \begin{code}
673 instance (Outputable id, Outputable pat) =>
674                 Outputable (ArithSeqInfo id pat) where
675     ppr (From e1)               = hcat [ppr e1, pp_dotdot]
676     ppr (FromThen e1 e2)        = hcat [ppr e1, comma, space, ppr e2, pp_dotdot]
677     ppr (FromTo e1 e3)  = hcat [ppr e1, pp_dotdot, ppr e3]
678     ppr (FromThenTo e1 e2 e3)
679       = hcat [ppr e1, comma, space, ppr e2, pp_dotdot, ppr e3]
680
681 pp_dotdot = ptext SLIT(" .. ")
682 \end{code}
683
684
685 %************************************************************************
686 %*                                                                      *
687 \subsection{HsMatchCtxt}
688 %*                                                                      *
689 %************************************************************************
690
691 \begin{code}
692 data HsMatchContext id  -- Context of a Match or Stmt
693   = DoCtxt HsDoContext  -- Do-stmt or list comprehension
694   | FunRhs id           -- Function binding for f
695   | CaseAlt             -- Guard on a case alternative
696   | LambdaExpr          -- Lambda
697   | PatBindRhs          -- Pattern binding
698   | RecUpd              -- Record update
699   deriving ()
700
701 data HsDoContext = ListComp 
702                  | DoExpr 
703                  | PArrComp     -- parallel array comprehension
704 \end{code}
705
706 \begin{code}
707 isDoExpr (DoCtxt DoExpr) = True
708 isDoExpr other           = False
709 \end{code}
710
711 \begin{code}
712 matchSeparator (FunRhs _)   = ptext SLIT("=")
713 matchSeparator CaseAlt      = ptext SLIT("->") 
714 matchSeparator LambdaExpr   = ptext SLIT("->") 
715 matchSeparator PatBindRhs   = ptext SLIT("=") 
716 matchSeparator (DoCtxt _)   = ptext SLIT("<-")  
717 matchSeparator RecUpd       = panic "When is this used?"
718 \end{code}
719
720 \begin{code}
721 pprMatchContext (FunRhs fun)      = ptext SLIT("In the definition of") <+> quotes (ppr fun)
722 pprMatchContext CaseAlt           = ptext SLIT("In a case alternative")
723 pprMatchContext RecUpd            = ptext SLIT("In a record-update construct")
724 pprMatchContext PatBindRhs        = ptext SLIT("In a pattern binding")
725 pprMatchContext LambdaExpr        = ptext SLIT("In a lambda abstraction")
726 pprMatchContext (DoCtxt DoExpr)   = ptext SLIT("In a 'do' expression pattern binding")
727 pprMatchContext (DoCtxt ListComp) = 
728   ptext SLIT("In a 'list comprehension' pattern binding")
729 pprMatchContext (DoCtxt PArrComp) = 
730   ptext SLIT("In an 'array comprehension' pattern binding")
731
732 -- Used to generate the string for a *runtime* error message
733 matchContextErrString (FunRhs fun)      = "function " ++ showSDoc (ppr fun)
734 matchContextErrString CaseAlt           = "case"
735 matchContextErrString PatBindRhs        = "pattern binding"
736 matchContextErrString RecUpd            = "record update"
737 matchContextErrString LambdaExpr        =  "lambda"
738 matchContextErrString (DoCtxt DoExpr)   = "'do' expression"
739 matchContextErrString (DoCtxt ListComp) = "list comprehension"
740 matchContextErrString (DoCtxt PArrComp) = "array comprehension"
741 \end{code}