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