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