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