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