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