df81fe16fc2b2b2427ae01e72f50e8fee8fe674a
[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          ( HsGroup )
13 import HsPat            ( LPat )
14 import HsLit            ( HsLit(..), HsOverLit )
15 import HsTypes          ( LHsType, PostTcType, SyntaxName )
16 import HsImpExp         ( isOperator, pprHsVar )
17 import HsBinds          ( HsBindGroup )
18
19 -- others:
20 import Type             ( Type, pprParendType )
21 import Var              ( TyVar, Id )
22 import Name             ( Name )
23 import DataCon          ( DataCon )
24 import BasicTypes       ( IPName, Boxity, tupleParens, Fixity(..) )
25 import SrcLoc           ( Located(..), unLoc )
26 import Outputable       
27 import FastString
28 \end{code}
29
30
31 %************************************************************************
32 %*                                                                      *
33 \subsection{Expressions proper}
34 %*                                                                      *
35 %************************************************************************
36
37 \begin{code}
38 type LHsExpr id = Located (HsExpr id)
39
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       (LMatch  id)    -- lambda
47   | HsApp       (LHsExpr id)    -- application
48                 (LHsExpr 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       (LHsExpr id)    -- left operand
57                 (LHsExpr id)    -- operator
58                 Fixity          -- Renamer adds fixity; bottom until then
59                 (LHsExpr 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      (LHsExpr id)    -- negated expr
65                 SyntaxName      -- Name of 'negate' (see RnEnv.lookupSyntaxName)
66
67   | HsPar       (LHsExpr id)    -- parenthesised expr
68
69   | SectionL    (LHsExpr id)    -- operand
70                 (LHsExpr id)    -- operator
71   | SectionR    (LHsExpr id)    -- operator
72                 (LHsExpr id)    -- operand
73                                 
74   | HsCase      (LHsExpr id)
75                 [LMatch id]
76
77   | HsIf        (LHsExpr id)    --  predicate
78                 (LHsExpr id)    --  then part
79                 (LHsExpr id)    --  else part
80
81   | HsLet       [HsBindGroup id] -- let(rec)
82                 (LHsExpr  id)
83
84   | HsDo        (HsStmtContext Name)    -- The parameterisation is unimportant
85                                         -- because in this context we never use
86                                         -- the PatGuard or ParStmt variant
87                 [LStmt id]              -- "do":one or more stmts
88                 (ReboundNames id)       -- Ids for [return,fail,>>=,>>]
89                         PostTcType      -- Type of the whole expression
90
91   | ExplicitList                -- syntactic list
92                 PostTcType      -- Gives type of components of list
93                 [LHsExpr id]
94
95   | ExplicitPArr                -- syntactic parallel array: [:e1, ..., en:]
96                 PostTcType      -- type of elements of the parallel array
97                 [LHsExpr id]
98
99   | ExplicitTuple               -- tuple
100                 [LHsExpr id]
101                                 -- NB: Unit is ExplicitTuple []
102                                 -- for tuples, we can get the types
103                                 -- direct from the components
104                 Boxity
105
106
107         -- Record construction
108   | RecordCon   (Located id)            -- The constructor
109                 (HsRecordBinds id)
110
111   | RecordConOut DataCon
112                 (LHsExpr id)            -- Data con Id applied to type args
113                 (HsRecordBinds id)
114
115
116         -- Record update
117   | RecordUpd   (LHsExpr id)
118                 (HsRecordBinds id)
119
120   | RecordUpdOut (LHsExpr id)   -- TRANSLATION
121                  Type                   -- Type of *input* record
122                  Type                   -- Type of *result* record (may differ from
123                                         --      type of input record)
124                  (HsRecordBinds id)
125
126   | ExprWithTySig                       -- signature binding
127                 (LHsExpr id)
128                 (LHsType id)
129   | ArithSeqIn                          -- arithmetic sequence
130                 (ArithSeqInfo id)
131   | ArithSeqOut
132                 (LHsExpr id)            -- (typechecked, of course)
133                 (ArithSeqInfo id)
134   | PArrSeqIn                           -- arith. sequence for parallel array
135                 (ArithSeqInfo id)       -- [:e1..e2:] or [:e1, e2..e3:]
136   | PArrSeqOut
137                 (LHsExpr id)            -- (typechecked, of course)
138                 (ArithSeqInfo id)
139
140   | HsSCC       FastString      -- "set cost centre" (_scc_) annotation
141                 (LHsExpr id)    -- expr whose cost is to be measured
142
143   | HsCoreAnn   FastString      -- hdaume: core annotation
144                 (LHsExpr id)
145                 
146   -----------------------------------------------------------
147   -- MetaHaskell Extensions
148   | HsBracket    (HsBracket id)
149
150   | HsBracketOut (HsBracket Name)       -- Output of the type checker is the *original*
151                  [PendingSplice]        -- renamed expression, plus *typechecked* splices
152                                         -- to be pasted back in by the desugarer
153
154   | HsSpliceE (HsSplice id) 
155
156   -----------------------------------------------------------
157   -- Arrow notation extension
158
159   | HsProc      (LPat id)               -- arrow abstraction, proc
160                 (LHsCmdTop id)          -- body of the abstraction
161                                         -- always has an empty stack
162
163   ---------------------------------------
164   -- The following are commands, not expressions proper
165
166   | HsArrApp    -- Arrow tail, or arrow application (f -< arg)
167         (LHsExpr id)    -- arrow expression, f
168         (LHsExpr id)    -- input expression, arg
169         PostTcType      -- type of the arrow expressions f,
170                         -- of the form a t t', where arg :: t
171         HsArrAppType    -- higher-order (-<<) or first-order (-<)
172         Bool            -- True => right-to-left (f -< arg)
173                         -- False => left-to-right (arg >- f)
174
175   | HsArrForm   -- Command formation,  (| e cmd1 .. cmdn |)
176         (LHsExpr id)    -- the operator
177                         -- after type-checking, a type abstraction to be
178                         -- applied to the type of the local environment tuple
179         (Maybe Fixity)  -- fixity (filled in by the renamer), for forms that
180                         -- were converted from OpApp's by the renamer
181         [LHsCmdTop id]  -- argument commands
182 \end{code}
183
184
185 These constructors only appear temporarily in the parser.
186 The renamer translates them into the Right Thing.
187
188 \begin{code}
189   | EWildPat                    -- wildcard
190
191   | EAsPat      (Located id)    -- as pattern
192                 (LHsExpr id)
193
194   | ELazyPat    (LHsExpr id) -- ~ pattern
195
196   | HsType      (LHsType id)     -- Explicit type argument; e.g  f {| Int |} x y
197 \end{code}
198
199 Everything from here on appears only in typechecker output.
200
201 \begin{code}
202   | TyLam                       -- TRANSLATION
203                 [TyVar]
204                 (LHsExpr id)
205   | TyApp                       -- TRANSLATION
206                 (LHsExpr id) -- generated by Spec
207                 [Type]
208
209   -- DictLam and DictApp are "inverses"
210   |  DictLam
211                 [id]
212                 (LHsExpr id)
213   |  DictApp
214                 (LHsExpr id)
215                 [id]
216
217 type PendingSplice = (Name, LHsExpr Id) -- Typechecked splices, waiting to be 
218                                         -- pasted back in by the desugarer
219 \end{code}
220
221 Table of bindings of names used in rebindable syntax.
222 This gets filled in by the renamer.
223
224 \begin{code}
225 type ReboundNames id = [(Name, HsExpr id)]
226 -- * Before the renamer, this list is empty
227 --
228 -- * After the renamer, it takes the form [(std_name, HsVar actual_name)]
229 --   For example, for the 'return' op of a monad
230 --      normal case:            (GHC.Base.return, HsVar GHC.Base.return)
231 --      with rebindable syntax: (GHC.Base.return, return_22)
232 --              where return_22 is whatever "return" is in scope
233 --
234 -- * After the type checker, it takes the form [(std_name, <expression>)]
235 --      where <expression> is the evidence for the method
236 \end{code}
237
238 A @Dictionary@, unless of length 0 or 1, becomes a tuple.  A
239 @ClassDictLam dictvars methods expr@ is, therefore:
240 \begin{verbatim}
241 \ x -> case x of ( dictvars-and-methods-tuple ) -> expr
242 \end{verbatim}
243
244 \begin{code}
245 instance OutputableBndr id => Outputable (HsExpr id) where
246     ppr expr = pprExpr expr
247 \end{code}
248
249 \begin{code}
250 pprExpr :: OutputableBndr id => HsExpr id -> SDoc
251
252 pprExpr  e = pprDeeper (ppr_expr e)
253
254 pprBinds :: OutputableBndr id => [HsBindGroup id] -> SDoc
255 pprBinds b = pprDeeper (vcat (map ppr b))
256
257 ppr_lexpr :: OutputableBndr id => LHsExpr id -> SDoc
258 ppr_lexpr e = ppr_expr (unLoc e)
259
260 ppr_expr (HsVar v)       = pprHsVar v
261 ppr_expr (HsIPVar v)     = ppr v
262 ppr_expr (HsLit lit)     = ppr lit
263 ppr_expr (HsOverLit lit) = ppr lit
264
265 ppr_expr (HsLam match) = pprMatch LambdaExpr (unLoc match)
266
267 ppr_expr (HsApp e1 e2)
268   = let (fun, args) = collect_args e1 [e2] in
269     (ppr_lexpr fun) <+> (sep (map pprParendExpr args))
270   where
271     collect_args (L _ (HsApp fun arg)) args = collect_args fun (arg:args)
272     collect_args fun args = (fun, args)
273
274 ppr_expr (OpApp e1 op fixity e2)
275   = case unLoc op of
276       HsVar v -> pp_infixly v
277       _       -> pp_prefixly
278   where
279     pp_e1 = pprParendExpr e1            -- Add parens to make precedence clear
280     pp_e2 = pprParendExpr e2
281
282     pp_prefixly
283       = hang (ppr op) 4 (sep [pp_e1, pp_e2])
284
285     pp_infixly v
286       = sep [pp_e1, hsep [pprInfix v, pp_e2]]
287
288 ppr_expr (NegApp e _) = char '-' <+> pprParendExpr e
289
290 ppr_expr (HsPar e) = parens (ppr_lexpr e)
291
292 ppr_expr (SectionL expr op)
293   = case unLoc op of
294       HsVar v -> pp_infixly v
295       _       -> pp_prefixly
296   where
297     pp_expr = pprParendExpr expr
298
299     pp_prefixly = hang (hsep [text " \\ x_ ->", ppr op])
300                        4 (hsep [pp_expr, ptext SLIT("x_ )")])
301     pp_infixly v = parens (sep [pp_expr, ppr v])
302
303 ppr_expr (SectionR op expr)
304   = case unLoc op of
305       HsVar v -> pp_infixly v
306       _       -> pp_prefixly
307   where
308     pp_expr = pprParendExpr expr
309
310     pp_prefixly = hang (hsep [text "( \\ x_ ->", ppr op, ptext SLIT("x_")])
311                        4 ((<>) pp_expr rparen)
312     pp_infixly v
313       = parens (sep [ppr v, pp_expr])
314
315 ppr_expr (HsCase expr matches)
316   = sep [ sep [ptext SLIT("case"), nest 4 (ppr expr), ptext SLIT("of")],
317             nest 2 (pprMatches CaseAlt matches) ]
318
319 ppr_expr (HsIf e1 e2 e3)
320   = sep [hsep [ptext SLIT("if"), nest 2 (ppr e1), ptext SLIT("then")],
321            nest 4 (ppr e2),
322            ptext SLIT("else"),
323            nest 4 (ppr e3)]
324
325 -- special case: let ... in let ...
326 ppr_expr (HsLet binds expr@(L _ (HsLet _ _)))
327   = sep [hang (ptext SLIT("let")) 2 (hsep [pprBinds binds, ptext SLIT("in")]),
328          ppr_lexpr expr]
329
330 ppr_expr (HsLet binds expr)
331   = sep [hang (ptext SLIT("let")) 2 (pprBinds binds),
332          hang (ptext SLIT("in"))  2 (ppr expr)]
333
334 ppr_expr (HsDo do_or_list_comp stmts _ _) = pprDo do_or_list_comp stmts
335
336 ppr_expr (ExplicitList _ exprs)
337   = brackets (fsep (punctuate comma (map ppr_lexpr exprs)))
338
339 ppr_expr (ExplicitPArr _ exprs)
340   = pa_brackets (fsep (punctuate comma (map ppr_lexpr exprs)))
341
342 ppr_expr (ExplicitTuple exprs boxity)
343   = tupleParens boxity (sep (punctuate comma (map ppr_lexpr exprs)))
344
345 ppr_expr (RecordCon con_id rbinds)
346   = pp_rbinds (ppr con_id) rbinds
347 ppr_expr (RecordConOut data_con con rbinds)
348   = pp_rbinds (ppr con) rbinds
349
350 ppr_expr (RecordUpd aexp rbinds)
351   = pp_rbinds (pprParendExpr aexp) rbinds
352 ppr_expr (RecordUpdOut aexp _ _ rbinds)
353   = pp_rbinds (pprParendExpr aexp) rbinds
354
355 ppr_expr (ExprWithTySig expr sig)
356   = hang (nest 2 (ppr_lexpr expr) <+> dcolon)
357          4 (ppr sig)
358
359 ppr_expr (ArithSeqIn info)
360   = brackets (ppr info)
361 ppr_expr (ArithSeqOut expr info)
362   = brackets (ppr info)
363
364 ppr_expr (PArrSeqIn info)
365   = pa_brackets (ppr info)
366 ppr_expr (PArrSeqOut expr info)
367   = pa_brackets (ppr info)
368
369 ppr_expr EWildPat = char '_'
370 ppr_expr (ELazyPat e) = char '~' <> pprParendExpr e
371 ppr_expr (EAsPat v e) = ppr v <> char '@' <> pprParendExpr e
372
373 ppr_expr (HsSCC lbl expr)
374   = sep [ ptext SLIT("_scc_") <+> doubleQuotes (ftext lbl), pprParendExpr expr ]
375
376 ppr_expr (TyLam tyvars expr)
377   = hang (hsep [ptext SLIT("/\\"), 
378                 hsep (map (pprBndr LambdaBind) tyvars), 
379                 ptext SLIT("->")])
380          4 (ppr_lexpr expr)
381
382 ppr_expr (TyApp expr [ty])
383   = hang (ppr_lexpr expr) 4 (pprParendType ty)
384
385 ppr_expr (TyApp expr tys)
386   = hang (ppr_lexpr expr)
387          4 (brackets (interpp'SP tys))
388
389 ppr_expr (DictLam dictvars expr)
390   = hang (hsep [ptext SLIT("\\{-dict-}"), 
391                 hsep (map (pprBndr LambdaBind) dictvars), 
392                 ptext SLIT("->")])
393          4 (ppr_lexpr expr)
394
395 ppr_expr (DictApp expr [dname])
396   = hang (ppr_lexpr expr) 4 (ppr dname)
397
398 ppr_expr (DictApp expr dnames)
399   = hang (ppr_lexpr expr)
400          4 (brackets (interpp'SP dnames))
401
402 ppr_expr (HsType id) = ppr id
403
404 ppr_expr (HsSpliceE s)       = pprSplice s
405 ppr_expr (HsBracket b)       = pprHsBracket b
406 ppr_expr (HsBracketOut e []) = ppr e    
407 ppr_expr (HsBracketOut e ps) = ppr e $$ ptext SLIT("pending") <+> ppr ps
408
409 ppr_expr (HsProc pat (L _ (HsCmdTop cmd _ _ _)))
410   = hsep [ptext SLIT("proc"), ppr pat, ptext SLIT("->"), ppr cmd]
411
412 ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp True)
413   = hsep [ppr_lexpr arrow, ptext SLIT("-<"), ppr_lexpr arg]
414 ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp False)
415   = hsep [ppr_lexpr arg, ptext SLIT(">-"), ppr_lexpr arrow]
416 ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp True)
417   = hsep [ppr_lexpr arrow, ptext SLIT("-<<"), ppr_lexpr arg]
418 ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp False)
419   = hsep [ppr_lexpr arg, ptext SLIT(">>-"), ppr_lexpr arrow]
420
421 ppr_expr (HsArrForm (L _ (HsVar v)) (Just _) [arg1, arg2])
422   = sep [pprCmdArg (unLoc arg1), hsep [pprInfix v, pprCmdArg (unLoc arg2)]]
423 ppr_expr (HsArrForm op _ args)
424   = hang (ptext SLIT("(|") <> ppr_lexpr op)
425          4 (sep (map (pprCmdArg.unLoc) args) <> ptext SLIT("|)"))
426
427 pprCmdArg :: OutputableBndr id => HsCmdTop id -> SDoc
428 pprCmdArg (HsCmdTop cmd@(L _ (HsArrForm _ Nothing [])) _ _ _)
429   = ppr_lexpr cmd
430 pprCmdArg (HsCmdTop cmd _ _ _)
431   = parens (ppr_lexpr cmd)
432
433 -- Put a var in backquotes if it's not an operator already
434 pprInfix :: Outputable name => name -> SDoc
435 pprInfix v | isOperator ppr_v = ppr_v
436            | otherwise        = char '`' <> ppr_v <> char '`'
437            where
438              ppr_v = ppr v
439
440 -- add parallel array brackets around a document
441 --
442 pa_brackets :: SDoc -> SDoc
443 pa_brackets p = ptext SLIT("[:") <> p <> ptext SLIT(":]")    
444 \end{code}
445
446 Parenthesize unless very simple:
447 \begin{code}
448 pprParendExpr :: OutputableBndr id => LHsExpr id -> SDoc
449 pprParendExpr expr
450   = let
451         pp_as_was = ppr_lexpr expr
452         -- Using ppr_expr here avoids the call to 'deeper'
453         -- Not sure if that's always right.
454     in
455     case unLoc expr of
456       HsLit l           -> ppr l
457       HsOverLit l       -> ppr l
458                         
459       HsVar _           -> pp_as_was
460       HsIPVar _         -> pp_as_was
461       ExplicitList _ _  -> pp_as_was
462       ExplicitPArr _ _  -> pp_as_was
463       ExplicitTuple _ _ -> pp_as_was
464       HsPar _           -> pp_as_was
465       HsBracket _       -> pp_as_was
466       HsBracketOut _ [] -> pp_as_was
467                         
468       _                 -> parens pp_as_was
469 \end{code}
470
471 %************************************************************************
472 %*                                                                      *
473 \subsection{Commands (in arrow abstractions)}
474 %*                                                                      *
475 %************************************************************************
476
477 We re-use HsExpr to represent these.
478
479 \begin{code}
480 type HsCmd id = HsExpr id
481
482 type LHsCmd id = LHsExpr id
483
484 data HsArrAppType = HsHigherOrderApp | HsFirstOrderApp
485 \end{code}
486
487 The legal constructors for commands are:
488
489   = HsArrApp ...                -- as above
490
491   | HsArrForm ...               -- as above
492
493   | HsApp       (HsCmd id)
494                 (HsExpr id)
495
496   | HsLam       (Match  id)     -- kappa
497
498   -- the renamer turns this one into HsArrForm
499   | OpApp       (HsExpr id)     -- left operand
500                 (HsCmd id)      -- operator
501                 Fixity          -- Renamer adds fixity; bottom until then
502                 (HsCmd id)      -- right operand
503
504   | HsPar       (HsCmd id)      -- parenthesised command
505
506   | HsCase      (HsExpr id)
507                 [Match id]      -- bodies are HsCmd's
508                 SrcLoc
509
510   | HsIf        (HsExpr id)     --  predicate
511                 (HsCmd id)      --  then part
512                 (HsCmd id)      --  else part
513                 SrcLoc
514
515   | HsLet       (HsBinds id)    -- let(rec)
516                 (HsCmd  id)
517
518   | HsDo        (HsStmtContext Name)    -- The parameterisation is unimportant
519                                         -- because in this context we never use
520                                         -- the PatGuard or ParStmt variant
521                 [Stmt id]       -- HsExpr's are really HsCmd's
522                 (ReboundNames id)
523                 PostTcType      -- Type of the whole expression
524                 SrcLoc
525
526 Top-level command, introducing a new arrow.
527 This may occur inside a proc (where the stack is empty) or as an
528 argument of a command-forming operator.
529
530 \begin{code}
531 type LHsCmdTop id = Located (HsCmdTop id)
532
533 data HsCmdTop id
534   = HsCmdTop    (LHsCmd id)
535                 [PostTcType]    -- types of inputs on the command's stack
536                 PostTcType      -- return type of the command
537                 (ReboundNames id)
538                                 -- after type checking:
539                                 -- names used in the command's desugaring
540 \end{code}
541
542 %************************************************************************
543 %*                                                                      *
544 \subsection{Record binds}
545 %*                                                                      *
546 %************************************************************************
547
548 \begin{code}
549 type HsRecordBinds id = [(Located id, LHsExpr id)]
550
551 recBindFields :: HsRecordBinds id -> [id]
552 recBindFields rbinds = [unLoc field | (field,_) <- rbinds]
553
554 pp_rbinds :: OutputableBndr id => SDoc -> HsRecordBinds id -> SDoc
555 pp_rbinds thing rbinds
556   = hang thing 
557          4 (braces (sep (punctuate comma (map (pp_rbind) rbinds))))
558   where
559     pp_rbind (v, e) = hsep [pprBndr LetBind (unLoc v), char '=', ppr e]
560 \end{code}
561
562
563
564 %************************************************************************
565 %*                                                                      *
566 \subsection{@Match@, @GRHSs@, and @GRHS@ datatypes}
567 %*                                                                      *
568 %************************************************************************
569
570 @Match@es are sets of pattern bindings and right hand sides for
571 functions, patterns or case branches. For example, if a function @g@
572 is defined as:
573 \begin{verbatim}
574 g (x,y) = y
575 g ((x:ys),y) = y+1,
576 \end{verbatim}
577 then \tr{g} has two @Match@es: @(x,y) = y@ and @((x:ys),y) = y+1@.
578
579 It is always the case that each element of an @[Match]@ list has the
580 same number of @pats@s inside it.  This corresponds to saying that
581 a function defined by pattern matching must have the same number of
582 patterns in each equation.
583
584 \begin{code}
585 type LMatch id = Located (Match id)
586
587 data Match id
588   = Match
589         [LPat id]               -- The patterns
590         (Maybe (LHsType id))    -- A type signature for the result of the match
591                                 --      Nothing after typechecking
592
593         (GRHSs id)
594
595 -- GRHSs are used both for pattern bindings and for Matches
596 data GRHSs id   
597   = GRHSs [LGRHS id]            -- Guarded RHSs
598           [HsBindGroup id]      -- The where clause
599           PostTcType            -- Type of RHS (after type checking)
600
601 type LGRHS id = Located (GRHS id)
602
603 data GRHS id
604   = GRHS  [LStmt id]            -- The RHS is the final ResultStmt
605 \end{code}
606
607 We know the list must have at least one @Match@ in it.
608
609 \begin{code}
610 pprMatches :: (OutputableBndr id) => HsMatchContext id -> [LMatch id] -> SDoc
611 pprMatches ctxt matches = vcat (map (pprMatch ctxt) (map unLoc matches))
612
613 -- Exported to HsBinds, which can't see the defn of HsMatchContext
614 pprFunBind :: (OutputableBndr id) => id -> [LMatch id] -> SDoc
615 pprFunBind fun matches = pprMatches (FunRhs fun) matches
616
617 -- Exported to HsBinds, which can't see the defn of HsMatchContext
618 pprPatBind :: (OutputableBndr id)
619            => LPat id -> GRHSs id -> SDoc
620 pprPatBind pat grhss = sep [ppr pat, nest 4 (pprGRHSs PatBindRhs grhss)]
621
622
623 pprMatch :: OutputableBndr id => HsMatchContext id -> Match id -> SDoc
624 pprMatch ctxt (Match pats maybe_ty grhss)
625   = pp_name ctxt <+> sep [sep (map ppr pats), 
626                      ppr_maybe_ty,
627                      nest 2 (pprGRHSs ctxt grhss)]
628   where
629     pp_name (FunRhs fun) = ppr fun      -- Not pprBndr; the AbsBinds will
630                                         -- have printed the signature
631     pp_name LambdaExpr   = char '\\'
632     pp_name other        = empty
633
634     ppr_maybe_ty = case maybe_ty of
635                         Just ty -> dcolon <+> ppr ty
636                         Nothing -> empty
637
638
639 pprGRHSs :: OutputableBndr id => HsMatchContext id -> GRHSs id -> SDoc
640 pprGRHSs ctxt (GRHSs grhss binds ty)
641   = vcat (map (pprGRHS ctxt . unLoc) grhss)
642     $$
643     (if null binds then empty
644      else text "where" $$ nest 4 (pprBinds binds))
645
646 pprGRHS :: OutputableBndr id => HsMatchContext id -> GRHS id -> SDoc
647
648 pprGRHS ctxt (GRHS [L _ (ResultStmt expr)])
649  =  pp_rhs ctxt expr
650
651 pprGRHS ctxt (GRHS guarded)
652  = sep [char '|' <+> interpp'SP guards, pp_rhs ctxt expr]
653  where
654     ResultStmt expr = unLoc (last guarded)
655         -- Last stmt should be a ResultStmt for guards
656     guards          = init guarded
657
658 pp_rhs ctxt rhs = matchSeparator ctxt <+> pprDeeper (ppr rhs)
659 \end{code}
660
661 %************************************************************************
662 %*                                                                      *
663 \subsection{Do stmts and list comprehensions}
664 %*                                                                      *
665 %************************************************************************
666
667 \begin{code}
668 type LStmt id = Located (Stmt id)
669
670 data Stmt id
671   = BindStmt    (LPat id) (LHsExpr id)
672   | LetStmt     [HsBindGroup id]
673   | ResultStmt  (LHsExpr id)                    -- See notes that follow
674   | ExprStmt    (LHsExpr id)    PostTcType      -- See notes that follow
675         -- The type is the *element type* of the expression
676
677         -- ParStmts only occur in a list comprehension
678   | ParStmt     [([LStmt id], [id])]    -- After remaing, the ids are the binders
679                                         -- bound by the stmts and used subsequently
680
681         -- Recursive statement
682   | RecStmt  [LStmt id] 
683                 --- The next two fields are only valid after renaming
684              [id]       -- The ids are a subset of the variables bound by the stmts
685                         -- that are used in stmts that follow the RecStmt
686
687              [id]       -- Ditto, but these variables are the "recursive" ones, that 
688                         -- are used before they are bound in the stmts of the RecStmt
689                         -- From a type-checking point of view, these ones have to be monomorphic
690
691                 --- This field is only valid after typechecking
692              [LHsExpr id]       -- These expressions correspond
693                                 -- 1-to-1 with the "recursive" [id], and are the expresions that 
694                                 -- should be returned by the recursion.  They may not quite be the
695                                 -- Ids themselves, because the Id may be *polymorphic*, but
696                                 -- the returned thing has to be *monomorphic*.
697 \end{code}
698
699 ExprStmts and ResultStmts are a bit tricky, because what they mean
700 depends on the context.  Consider the following contexts:
701
702         A do expression of type (m res_ty)
703         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
704         * ExprStmt E any_ty:   do { ....; E; ... }
705                 E :: m any_ty
706           Translation: E >> ...
707         
708         * ResultStmt E:   do { ....; E }
709                 E :: m res_ty
710           Translation: E
711         
712         A list comprehensions of type [elt_ty]
713         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
714         * ExprStmt E Bool:   [ .. | .... E ]
715                         [ .. | ..., E, ... ]
716                         [ .. | .... | ..., E | ... ]
717                 E :: Bool
718           Translation: if E then fail else ...
719
720         * ResultStmt E:   [ E | ... ]
721                 E :: elt_ty
722           Translation: return E
723         
724         A guard list, guarding a RHS of type rhs_ty
725         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
726         * ExprStmt E Bool:   f x | ..., E, ... = ...rhs...
727                 E :: Bool
728           Translation: if E then fail else ...
729         
730         * ResultStmt E:   f x | ...guards... = E
731                 E :: rhs_ty
732           Translation: E
733
734 Array comprehensions are handled like list comprehensions -=chak
735
736 \begin{code}
737 instance OutputableBndr id => Outputable (Stmt id) where
738     ppr stmt = pprStmt stmt
739
740 pprStmt (BindStmt pat expr)     = hsep [ppr pat, ptext SLIT("<-"), ppr expr]
741 pprStmt (LetStmt binds)         = hsep [ptext SLIT("let"), pprBinds binds]
742 pprStmt (ExprStmt expr _)       = ppr expr
743 pprStmt (ResultStmt expr)       = ppr expr
744 pprStmt (ParStmt stmtss)        = hsep (map (\stmts -> ptext SLIT("| ") <> ppr stmts) stmtss)
745 pprStmt (RecStmt segment _ _ _) = ptext SLIT("rec") <+> braces (vcat (map ppr segment))
746
747 pprDo :: OutputableBndr id => HsStmtContext any -> [LStmt id] -> SDoc
748 pprDo DoExpr stmts   = hang (ptext SLIT("do")) 2 (vcat (map ppr stmts))
749 pprDo MDoExpr stmts  = hang (ptext SLIT("mdo")) 3 (vcat (map ppr stmts))
750 pprDo ListComp stmts = pprComp brackets   stmts
751 pprDo PArrComp stmts = pprComp pa_brackets stmts
752
753 pprComp :: OutputableBndr id => (SDoc -> SDoc) -> [LStmt id] -> SDoc
754 pprComp brack stmts
755   = brack $
756         hang (ppr expr <+> char '|')
757              4 (interpp'SP quals)
758   where
759       ResultStmt expr = unLoc (last stmts)  -- Last stmt should
760       quals           = init stmts  -- be an ResultStmt
761 \end{code}
762
763 %************************************************************************
764 %*                                                                      *
765                 Template Haskell quotation brackets
766 %*                                                                      *
767 %************************************************************************
768
769 \begin{code}
770 data HsSplice id  = HsSplice    -- $z  or $(f 4)
771                         id              -- The id is just a unique name to 
772                         (LHsExpr id)    -- identify this splice point
773                                         
774 instance OutputableBndr id => Outputable (HsSplice id) where
775   ppr = pprSplice
776
777 pprSplice :: OutputableBndr id => HsSplice id -> SDoc
778 pprSplice (HsSplice n e) = char '$' <> brackets (ppr n) <> pprParendExpr e
779
780
781 data HsBracket id = ExpBr (LHsExpr id)          -- [|  expr  |]
782                   | PatBr (LPat id)             -- [p| pat   |]
783                   | DecBr (HsGroup id)          -- [d| decls |]
784                   | TypBr (LHsType id)          -- [t| type  |]
785                   | VarBr id                    -- 'x, ''T
786
787 instance OutputableBndr id => Outputable (HsBracket id) where
788   ppr = pprHsBracket
789
790
791 pprHsBracket (ExpBr e) = thBrackets empty (ppr e)
792 pprHsBracket (PatBr p) = thBrackets (char 'p') (ppr p)
793 pprHsBracket (DecBr d) = thBrackets (char 'd') (ppr d)
794 pprHsBracket (TypBr t) = thBrackets (char 't') (ppr t)
795 pprHsBracket (VarBr n) = char '\'' <> ppr n
796         -- Infelicity: can't show ' vs '', because
797         -- we can't ask n what its OccName is, because the 
798         -- pretty-printer for HsExpr doesn't ask for NamedThings
799         -- But the pretty-printer for names will show the OccName class
800
801 thBrackets pp_kind pp_body = char '[' <> pp_kind <> char '|' <+> 
802                              pp_body <+> ptext SLIT("|]")
803 \end{code}
804
805 %************************************************************************
806 %*                                                                      *
807 \subsection{Enumerations and list comprehensions}
808 %*                                                                      *
809 %************************************************************************
810
811 \begin{code}
812 data ArithSeqInfo id
813   = From            (LHsExpr id)
814   | FromThen        (LHsExpr id)
815                     (LHsExpr id)
816   | FromTo          (LHsExpr id)
817                     (LHsExpr id)
818   | FromThenTo      (LHsExpr id)
819                     (LHsExpr id)
820                     (LHsExpr id)
821 \end{code}
822
823 \begin{code}
824 instance OutputableBndr id => Outputable (ArithSeqInfo id) where
825     ppr (From e1)               = hcat [ppr e1, pp_dotdot]
826     ppr (FromThen e1 e2)        = hcat [ppr e1, comma, space, ppr e2, pp_dotdot]
827     ppr (FromTo e1 e3)  = hcat [ppr e1, pp_dotdot, ppr e3]
828     ppr (FromThenTo e1 e2 e3)
829       = hcat [ppr e1, comma, space, ppr e2, pp_dotdot, ppr e3]
830
831 pp_dotdot = ptext SLIT(" .. ")
832 \end{code}
833
834
835 %************************************************************************
836 %*                                                                      *
837 \subsection{HsMatchCtxt}
838 %*                                                                      *
839 %************************************************************************
840
841 \begin{code}
842 data HsMatchContext id  -- Context of a Match
843   = FunRhs id                   -- Function binding for f
844   | CaseAlt                     -- Guard on a case alternative
845   | LambdaExpr                  -- Pattern of a lambda
846   | ProcExpr                    -- Pattern of a proc
847   | PatBindRhs                  -- Pattern binding
848   | RecUpd                      -- Record update [used only in DsExpr to tell matchWrapper
849                                 --      what sort of runtime error message to generate]
850   | StmtCtxt (HsStmtContext id) -- Pattern of a do-stmt or list comprehension
851   deriving ()
852
853 data HsStmtContext id
854   = ListComp 
855   | DoExpr 
856   | MDoExpr                             -- Recursive do-expression
857   | PArrComp                            -- Parallel array comprehension
858   | PatGuard (HsMatchContext id)        -- Pattern guard for specified thing
859   | ParStmtCtxt (HsStmtContext id)      -- A branch of a parallel stmt 
860 \end{code}
861
862 \begin{code}
863 isDoExpr :: HsStmtContext id -> Bool
864 isDoExpr DoExpr  = True
865 isDoExpr MDoExpr = True
866 isDoExpr other   = False
867 \end{code}
868
869 \begin{code}
870 matchSeparator (FunRhs _)   = ptext SLIT("=")
871 matchSeparator CaseAlt      = ptext SLIT("->") 
872 matchSeparator LambdaExpr   = ptext SLIT("->") 
873 matchSeparator ProcExpr     = ptext SLIT("->") 
874 matchSeparator PatBindRhs   = ptext SLIT("=") 
875 matchSeparator (StmtCtxt _) = ptext SLIT("<-")  
876 matchSeparator RecUpd       = panic "unused"
877 \end{code}
878
879 \begin{code}
880 pprMatchContext (FunRhs fun)      = ptext SLIT("the definition of") <+> quotes (ppr fun)
881 pprMatchContext CaseAlt           = ptext SLIT("a case alternative")
882 pprMatchContext RecUpd            = ptext SLIT("a record-update construct")
883 pprMatchContext PatBindRhs        = ptext SLIT("a pattern binding")
884 pprMatchContext LambdaExpr        = ptext SLIT("a lambda abstraction")
885 pprMatchContext ProcExpr          = ptext SLIT("an arrow abstraction")
886 pprMatchContext (StmtCtxt ctxt)   = ptext SLIT("a pattern binding in") $$ pprStmtContext ctxt
887
888 pprMatchRhsContext (FunRhs fun) = ptext SLIT("a right-hand side of function") <+> quotes (ppr fun)
889 pprMatchRhsContext CaseAlt      = ptext SLIT("the body of a case alternative")
890 pprMatchRhsContext PatBindRhs   = ptext SLIT("the right-hand side of a pattern binding")
891 pprMatchRhsContext LambdaExpr   = ptext SLIT("the body of a lambda")
892 pprMatchRhsContext ProcExpr     = ptext SLIT("the body of a proc")
893 pprMatchRhsContext RecUpd       = panic "pprMatchRhsContext"
894
895 pprStmtContext (ParStmtCtxt c) = sep [ptext SLIT("a parallel branch of"), pprStmtContext c]
896 pprStmtContext (PatGuard ctxt) = ptext SLIT("a pattern guard for") $$ pprMatchContext ctxt
897 pprStmtContext DoExpr          = ptext SLIT("a 'do' expression")
898 pprStmtContext MDoExpr         = ptext SLIT("an 'mdo' expression")
899 pprStmtContext ListComp        = ptext SLIT("a list comprehension")
900 pprStmtContext PArrComp        = ptext SLIT("an array comprehension")
901
902 -- Used for the result statement of comprehension
903 -- e.g. the 'e' in      [ e | ... ]
904 --      or the 'r' in   f x = r
905 pprStmtResultContext (PatGuard ctxt) = pprMatchRhsContext ctxt
906 pprStmtResultContext other           = ptext SLIT("the result of") <+> pprStmtContext other
907
908
909 -- Used to generate the string for a *runtime* error message
910 matchContextErrString (FunRhs fun)               = "function " ++ showSDoc (ppr fun)
911 matchContextErrString CaseAlt                    = "case"
912 matchContextErrString PatBindRhs                 = "pattern binding"
913 matchContextErrString RecUpd                     = "record update"
914 matchContextErrString LambdaExpr                 = "lambda"
915 matchContextErrString ProcExpr                   = "proc"
916 matchContextErrString (StmtCtxt (ParStmtCtxt c)) = matchContextErrString (StmtCtxt c)
917 matchContextErrString (StmtCtxt (PatGuard _))    = "pattern guard"
918 matchContextErrString (StmtCtxt DoExpr)          = "'do' expression"
919 matchContextErrString (StmtCtxt MDoExpr)         = "'mdo' expression"
920 matchContextErrString (StmtCtxt ListComp)        = "list comprehension"
921 matchContextErrString (StmtCtxt PArrComp)        = "array comprehension"
922 \end{code}