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