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