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