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