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