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