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