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