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