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