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