[project @ 2003-07-16 08:49:01 by ross]
[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 ForeignCall      ( Safety )
21 import PprType          ( pprParendType )
22 import Type             ( Type )
23 import Var              ( TyVar, Id )
24 import Name             ( Name )
25 import NameSet          ( FreeVars )
26 import DataCon          ( DataCon )
27 import CStrings         ( CLabelString, pprCLabelString )
28 import BasicTypes       ( IPName, Boxity, tupleParens, Fixity(..) )
29 import SrcLoc           ( SrcLoc )
30 import Outputable       
31 import FastString
32 \end{code}
33
34 %************************************************************************
35 %*                                                                      *
36 \subsection{Expressions proper}
37 %*                                                                      *
38 %************************************************************************
39
40 \begin{code}
41 data HsExpr id
42   = HsVar       id              -- variable
43   | HsIPVar     (IPName id)     -- implicit parameter
44   | HsOverLit   HsOverLit       -- Overloaded literals; eliminated by type checker
45   | HsLit       HsLit           -- Simple (non-overloaded) literals
46
47   | HsLam       (Match  id)     -- lambda
48   | HsApp       (HsExpr id)     -- application
49                 (HsExpr id)
50
51   -- Operator applications:
52   -- NB Bracketed ops such as (+) come out as Vars.
53
54   -- NB We need an expr for the operator in an OpApp/Section since
55   -- the typechecker may need to apply the operator to a few types.
56
57   | OpApp       (HsExpr id)     -- left operand
58                 (HsExpr id)     -- operator
59                 Fixity          -- Renamer adds fixity; bottom until then
60                 (HsExpr id)     -- right operand
61
62   -- We preserve prefix negation and parenthesis for the precedence parser.
63   -- They are eventually removed by the type checker.
64
65   | NegApp      (HsExpr id)     -- negated expr
66                 SyntaxName      -- Name of 'negate' (see RnEnv.lookupSyntaxName)
67
68   | HsPar       (HsExpr id)     -- parenthesised expr
69
70   | SectionL    (HsExpr id)     -- operand
71                 (HsExpr id)     -- operator
72   | SectionR    (HsExpr id)     -- operator
73                 (HsExpr id)     -- operand
74                                 
75   | HsCase      (HsExpr id)
76                 [Match id]
77                 SrcLoc
78
79   | HsIf        (HsExpr id)     --  predicate
80                 (HsExpr id)     --  then part
81                 (HsExpr id)     --  else part
82                 SrcLoc
83
84   | HsLet       (HsBinds id)    -- let(rec)
85                 (HsExpr  id)
86
87   | HsDo        (HsStmtContext Name)    -- The parameterisation is unimportant
88                                         -- because in this context we never use
89                                         -- the PatGuard or ParStmt variant
90                 [Stmt id]               -- "do":one or more stmts
91                 (ReboundNames id)       -- Ids for [return,fail,>>=,>>]
92                         PostTcType      -- Type of the whole expression
93                 SrcLoc
94
95   | ExplicitList                -- syntactic list
96                 PostTcType      -- Gives type of components of list
97                 [HsExpr id]
98
99   | ExplicitPArr                -- syntactic parallel array: [:e1, ..., en:]
100                 PostTcType      -- type of elements of the parallel array
101                 [HsExpr id]
102
103   | ExplicitTuple               -- tuple
104                 [HsExpr id]
105                                 -- NB: Unit is ExplicitTuple []
106                                 -- for tuples, we can get the types
107                                 -- direct from the components
108                 Boxity
109
110
111         -- Record construction
112   | RecordCon   id                              -- The constructor
113                 (HsRecordBinds id)
114
115   | RecordConOut DataCon
116                 (HsExpr id)             -- Data con Id applied to type args
117                 (HsRecordBinds id)
118
119
120         -- Record update
121   | RecordUpd   (HsExpr id)
122                 (HsRecordBinds id)
123
124   | RecordUpdOut (HsExpr id)    -- TRANSLATION
125                  Type                   -- Type of *input* record
126                  Type                   -- Type of *result* record (may differ from
127                                         --      type of input record)
128                  (HsRecordBinds id)
129
130   | ExprWithTySig                       -- signature binding
131                 (HsExpr id)
132                 (HsType id)
133   | ArithSeqIn                          -- arithmetic sequence
134                 (ArithSeqInfo id)
135   | ArithSeqOut
136                 (HsExpr id)             -- (typechecked, of course)
137                 (ArithSeqInfo id)
138   | PArrSeqIn                           -- arith. sequence for parallel array
139                 (ArithSeqInfo id)       -- [:e1..e2:] or [:e1, e2..e3:]
140   | PArrSeqOut
141                 (HsExpr id)             -- (typechecked, of course)
142                 (ArithSeqInfo id)
143
144   | HsCCall     CLabelString    -- call into the C world; string is
145                 [HsExpr id]     -- the C function; exprs are the
146                                 -- arguments to pass.
147                 Safety          -- True <=> might cause Haskell
148                                 -- garbage-collection (must generate
149                                 -- more paranoid code)
150                 Bool            -- True <=> it's really a "casm"
151                                 -- NOTE: this CCall is the *boxed*
152                                 -- version; the desugarer will convert
153                                 -- it into the unboxed "ccall#".
154                 PostTcType      -- The result type; will be *bottom*
155                                 -- until the typechecker gets ahold of it
156
157   | HsSCC       FastString      -- "set cost centre" (_scc_) annotation
158                 (HsExpr id)     -- expr whose cost is to be measured
159
160   | HsCoreAnn   FastString      -- hdaume: core annotation
161                 (HsExpr id)
162                 
163   -----------------------------------------------------------
164   -- MetaHaskell Extensions
165   | HsBracket    (HsBracket id) SrcLoc
166
167   | HsBracketOut (HsBracket Name)       -- Output of the type checker is the *original*
168                  [PendingSplice]        -- renamed expression, plus *typechecked* splices
169                                         -- to be pasted back in by the desugarer
170
171   | HsSplice id (HsExpr id) SrcLoc      -- $z  or $(f 4)
172                                         -- The id is just a unique name to 
173                                         -- identify this splice point
174
175   | HsReify (HsReify id)                -- reifyType t, reifyDecl i, reifyFixity
176
177   -----------------------------------------------------------
178   -- Arrow notation extension
179
180   | HsProc      (Pat id)                -- arrow abstraction, proc
181                 (HsCmdTop id)           -- body of the abstraction
182                                         -- always has an empty stack
183                 SrcLoc
184
185   ---------------------------------------
186   -- The following are commands, not expressions proper
187
188   | HsArrApp    -- Arrow tail, or arrow application (f -< arg)
189         (HsExpr id)     -- arrow expression, f
190         (HsExpr id)     -- input expression, arg
191         PostTcType      -- type of the arrow expressions f,
192                         -- of the form a t t', where arg :: t
193         HsArrAppType    -- higher-order (-<<) or first-order (-<)
194         Bool            -- True => right-to-left (f -< arg)
195                         -- False => left-to-right (arg >- f)
196         SrcLoc
197
198   | HsArrForm   -- Command formation,  (| e cmd1 .. cmdn |)
199         (HsExpr id)     -- the operator
200                         -- after type-checking, a type abstraction to be
201                         -- applied to the type of the local environment tuple
202         (Maybe Fixity)  -- fixity (filled in by the renamer), for forms that
203                         -- were converted from OpApp's by the renamer
204         [HsCmdTop id]   -- argument commands
205         SrcLoc
206
207 \end{code}
208
209
210 These constructors only appear temporarily in the parser.
211 The renamer translates them into the Right Thing.
212
213 \begin{code}
214   | EWildPat                    -- wildcard
215
216   | EAsPat      id              -- as pattern
217                 (HsExpr id)
218
219   | ELazyPat    (HsExpr id) -- ~ pattern
220
221   | HsType      (HsType id)     -- Explicit type argument; e.g  f {| Int |} x y
222 \end{code}
223
224 Everything from here on appears only in typechecker output.
225
226 \begin{code}
227   | TyLam                       -- TRANSLATION
228                 [TyVar]
229                 (HsExpr id)
230   | TyApp                       -- TRANSLATION
231                 (HsExpr id) -- generated by Spec
232                 [Type]
233
234   -- DictLam and DictApp are "inverses"
235   |  DictLam
236                 [id]
237                 (HsExpr id)
238   |  DictApp
239                 (HsExpr id)
240                 [id]
241
242 type PendingSplice = (Name, HsExpr Id)  -- Typechecked splices, waiting to be 
243                                         -- pasted back in by the desugarer
244 \end{code}
245
246 Table of bindings of names used in rebindable syntax.
247 This gets filled in by the renamer.
248
249 \begin{code}
250 type ReboundNames id = [(Name, HsExpr id)]
251 -- * Before the renamer, this list is empty
252 --
253 -- * After the renamer, it takes the form [(std_name, HsVar actual_name)]
254 --   For example, for the 'return' op of a monad
255 --      normal case:            (GHC.Base.return, HsVar GHC.Base.return)
256 --      with rebindable syntax: (GHC.Base.return, return_22)
257 --              where return_22 is whatever "return" is in scope
258 --
259 -- * After the type checker, it takes the form [(std_name, <expression>)]
260 --      where <expression> is the evidence for the method
261 \end{code}
262
263 A @Dictionary@, unless of length 0 or 1, becomes a tuple.  A
264 @ClassDictLam dictvars methods expr@ is, therefore:
265 \begin{verbatim}
266 \ x -> case x of ( dictvars-and-methods-tuple ) -> expr
267 \end{verbatim}
268
269 \begin{code}
270 instance OutputableBndr id => Outputable (HsExpr id) where
271     ppr expr = pprExpr expr
272 \end{code}
273
274 \begin{code}
275 pprExpr :: OutputableBndr id => HsExpr id -> SDoc
276
277 pprExpr  e = pprDeeper (ppr_expr e)
278 pprBinds b = pprDeeper (ppr b)
279
280 ppr_expr (HsVar v)       = pprHsVar v
281 ppr_expr (HsIPVar v)     = ppr v
282 ppr_expr (HsLit lit)     = ppr lit
283 ppr_expr (HsOverLit lit) = ppr lit
284
285 ppr_expr (HsLam match) = pprMatch LambdaExpr match
286
287 ppr_expr expr@(HsApp e1 e2)
288   = let (fun, args) = collect_args expr [] in
289     (ppr_expr fun) <+> (sep (map ppr_expr args))
290   where
291     collect_args (HsApp fun arg) args = collect_args fun (arg:args)
292     collect_args fun             args = (fun, args)
293
294 ppr_expr (OpApp e1 op fixity e2)
295   = case op of
296       HsVar v -> pp_infixly v
297       _       -> pp_prefixly
298   where
299     pp_e1 = pprParendExpr e1            -- Add parens to make precedence clear
300     pp_e2 = pprParendExpr e2
301
302     pp_prefixly
303       = hang (pprExpr op) 4 (sep [pp_e1, pp_e2])
304
305     pp_infixly v
306       = sep [pp_e1, hsep [pprInfix v, pp_e2]]
307
308 ppr_expr (NegApp e _) = char '-' <+> pprParendExpr e
309
310 ppr_expr (HsPar e) = parens (ppr_expr e)
311
312 ppr_expr (SectionL expr op)
313   = case op of
314       HsVar v -> pp_infixly v
315       _       -> pp_prefixly
316   where
317     pp_expr = pprParendExpr expr
318
319     pp_prefixly = hang (hsep [text " \\ x_ ->", ppr op])
320                        4 (hsep [pp_expr, ptext SLIT("x_ )")])
321     pp_infixly v = parens (sep [pp_expr, ppr v])
322
323 ppr_expr (SectionR op expr)
324   = case op of
325       HsVar v -> pp_infixly v
326       _       -> pp_prefixly
327   where
328     pp_expr = pprParendExpr expr
329
330     pp_prefixly = hang (hsep [text "( \\ x_ ->", ppr op, ptext SLIT("x_")])
331                        4 ((<>) pp_expr rparen)
332     pp_infixly v
333       = parens (sep [ppr v, pp_expr])
334
335 ppr_expr (HsCase expr matches _)
336   = sep [ sep [ptext SLIT("case"), nest 4 (pprExpr expr), ptext SLIT("of")],
337             nest 2 (pprMatches CaseAlt matches) ]
338
339 ppr_expr (HsIf e1 e2 e3 _)
340   = sep [hsep [ptext SLIT("if"), nest 2 (pprExpr e1), ptext SLIT("then")],
341            nest 4 (pprExpr e2),
342            ptext SLIT("else"),
343            nest 4 (pprExpr e3)]
344
345 -- special case: let ... in let ...
346 ppr_expr (HsLet binds expr@(HsLet _ _))
347   = sep [hang (ptext SLIT("let")) 2 (hsep [pprBinds binds, ptext SLIT("in")]),
348          pprExpr expr]
349
350 ppr_expr (HsLet binds expr)
351   = sep [hang (ptext SLIT("let")) 2 (pprBinds binds),
352          hang (ptext SLIT("in"))  2 (ppr expr)]
353
354 ppr_expr (HsDo do_or_list_comp stmts _ _ _) = pprDo do_or_list_comp stmts
355
356 ppr_expr (ExplicitList _ exprs)
357   = brackets (fsep (punctuate comma (map ppr_expr exprs)))
358
359 ppr_expr (ExplicitPArr _ exprs)
360   = pa_brackets (fsep (punctuate comma (map ppr_expr exprs)))
361
362 ppr_expr (ExplicitTuple exprs boxity)
363   = tupleParens boxity (sep (punctuate comma (map ppr_expr exprs)))
364
365 ppr_expr (RecordCon con_id rbinds)
366   = pp_rbinds (ppr con_id) rbinds
367 ppr_expr (RecordConOut data_con con rbinds)
368   = pp_rbinds (ppr con) rbinds
369
370 ppr_expr (RecordUpd aexp rbinds)
371   = pp_rbinds (pprParendExpr aexp) rbinds
372 ppr_expr (RecordUpdOut aexp _ _ rbinds)
373   = pp_rbinds (pprParendExpr aexp) rbinds
374
375 ppr_expr (ExprWithTySig expr sig)
376   = hang (nest 2 (ppr_expr expr) <+> dcolon)
377          4 (ppr sig)
378
379 ppr_expr (ArithSeqIn info)
380   = brackets (ppr info)
381 ppr_expr (ArithSeqOut expr info)
382   = brackets (ppr info)
383
384 ppr_expr (PArrSeqIn info)
385   = pa_brackets (ppr info)
386 ppr_expr (PArrSeqOut expr info)
387   = pa_brackets (ppr info)
388
389 ppr_expr EWildPat = char '_'
390 ppr_expr (ELazyPat e) = char '~' <> pprParendExpr e
391 ppr_expr (EAsPat v e) = ppr v <> char '@' <> pprParendExpr e
392
393 ppr_expr (HsCCall fun args _ is_asm result_ty)
394   = hang (if is_asm
395           then ptext SLIT("_casm_ ``") <> pprCLabelString fun <> ptext SLIT("''")
396           else ptext SLIT("_ccall_") <+> pprCLabelString fun)
397        4 (sep (map pprParendExpr args))
398
399 ppr_expr (HsSCC lbl expr)
400   = sep [ ptext SLIT("_scc_") <+> doubleQuotes (ftext lbl), pprParendExpr expr ]
401
402 ppr_expr (TyLam tyvars expr)
403   = hang (hsep [ptext SLIT("/\\"), 
404                 hsep (map (pprBndr LambdaBind) tyvars), 
405                 ptext SLIT("->")])
406          4 (ppr_expr expr)
407
408 ppr_expr (TyApp expr [ty])
409   = hang (ppr_expr expr) 4 (pprParendType ty)
410
411 ppr_expr (TyApp expr tys)
412   = hang (ppr_expr expr)
413          4 (brackets (interpp'SP tys))
414
415 ppr_expr (DictLam dictvars expr)
416   = hang (hsep [ptext SLIT("\\{-dict-}"), 
417                 hsep (map (pprBndr LambdaBind) dictvars), 
418                 ptext SLIT("->")])
419          4 (ppr_expr expr)
420
421 ppr_expr (DictApp expr [dname])
422   = hang (ppr_expr expr) 4 (ppr dname)
423
424 ppr_expr (DictApp expr dnames)
425   = hang (ppr_expr expr)
426          4 (brackets (interpp'SP dnames))
427
428 ppr_expr (HsType id) = ppr id
429
430 ppr_expr (HsSplice n e _)    = char '$' <> brackets (ppr n) <> pprParendExpr e
431 ppr_expr (HsBracket b _)     = pprHsBracket b
432 ppr_expr (HsBracketOut e ps) = ppr e $$ ptext SLIT("where") <+> ppr ps
433 ppr_expr (HsReify r)         = ppr r
434
435 ppr_expr (HsProc pat (HsCmdTop cmd _ _ _) _)
436   = hsep [ptext SLIT("proc"), ppr pat, ptext SLIT("->"), pprExpr cmd]
437
438 ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp True _)
439   = hsep [pprExpr arrow, ptext SLIT("-<"), pprExpr arg]
440 ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp False _)
441   = hsep [pprExpr arg, ptext SLIT(">-"), pprExpr arrow]
442 ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp True _)
443   = hsep [pprExpr arrow, ptext SLIT("-<<"), pprExpr arg]
444 ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp False _)
445   = hsep [pprExpr arg, ptext SLIT(">>-"), pprExpr arrow]
446
447 ppr_expr (HsArrForm (HsVar v) (Just _) [arg1, arg2] _)
448   = sep [pprCmdArg arg1, hsep [pprInfix v, pprCmdArg arg2]]
449 ppr_expr (HsArrForm op _ args _)
450   = hang (ptext SLIT("(|") <> pprExpr op)
451          4 (sep (map pprCmdArg args) <> ptext SLIT("|)"))
452
453 pprCmdArg :: OutputableBndr id => HsCmdTop id -> SDoc
454 pprCmdArg (HsCmdTop cmd@(HsArrForm _ Nothing [] _) _ _ _) = pprExpr cmd
455 pprCmdArg (HsCmdTop cmd _ _ _) = parens (pprExpr cmd)
456
457 -- Put a var in backquotes if it's not an operator already
458 pprInfix :: Outputable name => name -> SDoc
459 pprInfix v | isOperator ppr_v = ppr_v
460            | otherwise        = char '`' <> ppr_v <> char '`'
461            where
462              ppr_v = ppr v
463
464 -- add parallel array brackets around a document
465 --
466 pa_brackets :: SDoc -> SDoc
467 pa_brackets p = ptext SLIT("[:") <> p <> ptext SLIT(":]")    
468 \end{code}
469
470 Parenthesize unless very simple:
471 \begin{code}
472 pprParendExpr :: OutputableBndr id => HsExpr id -> SDoc
473
474 pprParendExpr expr
475   = let
476         pp_as_was = pprExpr expr
477     in
478     case expr of
479       HsLit l               -> ppr l
480       HsOverLit l           -> ppr l
481
482       HsVar _               -> pp_as_was
483       HsIPVar _             -> pp_as_was
484       ExplicitList _ _      -> pp_as_was
485       ExplicitPArr _ _      -> pp_as_was
486       ExplicitTuple _ _     -> pp_as_was
487       HsPar _               -> pp_as_was
488
489       _                     -> parens pp_as_was
490 \end{code}
491
492 %************************************************************************
493 %*                                                                      *
494 \subsection{Commands (in arrow abstractions)}
495 %*                                                                      *
496 %************************************************************************
497
498 We re-use HsExpr to represent these.
499
500 \begin{code}
501 type HsCmd id = HsExpr id
502
503 data HsArrAppType = HsHigherOrderApp | HsFirstOrderApp
504 \end{code}
505
506 The legal constructors for commands are:
507
508   = HsArrApp ...                -- as above
509
510   | HsArrForm ...               -- as above
511
512   | HsApp       (HsCmd id)
513                 (HsExpr id)
514
515   | HsLam       (Match  id)     -- kappa
516
517   -- the renamer turns this one into HsArrForm
518   | OpApp       (HsExpr id)     -- left operand
519                 (HsCmd id)      -- operator
520                 Fixity          -- Renamer adds fixity; bottom until then
521                 (HsCmd id)      -- right operand
522
523   | HsPar       (HsCmd id)      -- parenthesised command
524
525   | HsCase      (HsExpr id)
526                 [Match id]      -- bodies are HsCmd's
527                 SrcLoc
528
529   | HsIf        (HsExpr id)     --  predicate
530                 (HsCmd id)      --  then part
531                 (HsCmd id)      --  else part
532                 SrcLoc
533
534   | HsLet       (HsBinds id)    -- let(rec)
535                 (HsCmd  id)
536
537   | HsDo        (HsStmtContext Name)    -- The parameterisation is unimportant
538                                         -- because in this context we never use
539                                         -- the PatGuard or ParStmt variant
540                 [Stmt id]       -- HsExpr's are really HsCmd's
541                 (ReboundNames id)
542                 PostTcType      -- Type of the whole expression
543                 SrcLoc
544
545 Top-level command, introducing a new arrow.
546 This may occur inside a proc (where the stack is empty) or as an
547 argument of a command-forming operator.
548
549 \begin{code}
550 data HsCmdTop id
551   = HsCmdTop    (HsCmd id)
552                 [PostTcType]    -- types of inputs on the command's stack
553                 PostTcType      -- return type of the command
554                 (ReboundNames id)
555                                 -- after type checking:
556                                 -- names used in the command's desugaring
557 \end{code}
558
559 %************************************************************************
560 %*                                                                      *
561 \subsection{Record binds}
562 %*                                                                      *
563 %************************************************************************
564
565 \begin{code}
566 type HsRecordBinds id = [(id, HsExpr id)]
567
568 recBindFields :: HsRecordBinds id -> [id]
569 recBindFields rbinds = [field | (field,_) <- rbinds]
570
571 pp_rbinds :: OutputableBndr id => SDoc -> HsRecordBinds id -> SDoc
572
573 pp_rbinds thing rbinds
574   = hang thing 
575          4 (braces (sep (punctuate comma (map (pp_rbind) rbinds))))
576   where
577     pp_rbind (v, e) = hsep [pprBndr LetBind v, char '=', ppr e]
578 \end{code}
579
580
581
582 %************************************************************************
583 %*                                                                      *
584 \subsection{@Match@, @GRHSs@, and @GRHS@ datatypes}
585 %*                                                                      *
586 %************************************************************************
587
588 @Match@es are sets of pattern bindings and right hand sides for
589 functions, patterns or case branches. For example, if a function @g@
590 is defined as:
591 \begin{verbatim}
592 g (x,y) = y
593 g ((x:ys),y) = y+1,
594 \end{verbatim}
595 then \tr{g} has two @Match@es: @(x,y) = y@ and @((x:ys),y) = y+1@.
596
597 It is always the case that each element of an @[Match]@ list has the
598 same number of @pats@s inside it.  This corresponds to saying that
599 a function defined by pattern matching must have the same number of
600 patterns in each equation.
601
602 \begin{code}
603 data Match id
604   = Match
605         [Pat id]                -- The patterns
606         (Maybe (HsType id))     -- A type signature for the result of the match
607                                 --      Nothing after typechecking
608
609         (GRHSs id)
610
611 -- GRHSs are used both for pattern bindings and for Matches
612 data GRHSs id   
613   = GRHSs [GRHS id]             -- Guarded RHSs
614           (HsBinds id)          -- The where clause
615           PostTcType            -- Type of RHS (after type checking)
616
617 data GRHS id
618   = GRHS  [Stmt id]             -- The RHS is the final ResultStmt
619           SrcLoc
620
621 mkSimpleMatch :: [Pat id] -> HsExpr id -> Type -> SrcLoc -> Match id
622 mkSimpleMatch pats rhs rhs_ty locn
623   = Match pats Nothing (GRHSs (unguardedRHS rhs locn) EmptyBinds rhs_ty)
624
625 unguardedRHS :: HsExpr id -> SrcLoc -> [GRHS id]
626 unguardedRHS rhs loc = [GRHS [ResultStmt rhs loc] loc]
627
628 glueBindsOnGRHSs :: HsBinds id -> GRHSs id -> GRHSs id
629 glueBindsOnGRHSs EmptyBinds grhss = grhss
630 glueBindsOnGRHSs binds1 (GRHSs grhss binds2 ty)
631   = GRHSs grhss (binds1 `ThenBinds` binds2) ty
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)
812                   | PatBr (Pat id)
813                   | DecBr (HsGroup id)
814                   | TypBr (HsType id)
815
816 instance OutputableBndr id => Outputable (HsBracket id) where
817   ppr = pprHsBracket
818
819
820 pprHsBracket (ExpBr e) = thBrackets empty (ppr e)
821 pprHsBracket (PatBr p) = thBrackets (char 'p') (ppr p)
822 pprHsBracket (DecBr d) = thBrackets (char 'd') (ppr d)
823 pprHsBracket (TypBr t) = thBrackets (char 't') (ppr t)
824
825
826 thBrackets pp_kind pp_body = char '[' <> pp_kind <> char '|' <+> 
827                              pp_body <+> ptext SLIT("|]")
828
829 data HsReify id = Reify    ReifyFlavour id      -- Pre typechecking
830                 | ReifyOut ReifyFlavour Name    -- Post typechecking
831                                                 -- The Name could be the name of
832                                                 -- an Id, TyCon, or Class
833
834 data ReifyFlavour = ReifyDecl | ReifyType | ReifyFixity
835
836 instance Outputable id => Outputable (HsReify id) where
837    ppr (Reify flavour id) = ppr flavour <+> ppr id
838    ppr (ReifyOut flavour thing) = ppr flavour <+> ppr thing
839
840 instance Outputable ReifyFlavour where
841    ppr ReifyDecl   = ptext SLIT("reifyDecl")
842    ppr ReifyType   = ptext SLIT("reifyType")
843    ppr ReifyFixity = ptext SLIT("reifyFixity")
844 \end{code}
845
846 %************************************************************************
847 %*                                                                      *
848 \subsection{Enumerations and list comprehensions}
849 %*                                                                      *
850 %************************************************************************
851
852 \begin{code}
853 data ArithSeqInfo id
854   = From            (HsExpr id)
855   | FromThen        (HsExpr id)
856                     (HsExpr id)
857   | FromTo          (HsExpr id)
858                     (HsExpr id)
859   | FromThenTo      (HsExpr id)
860                     (HsExpr id)
861                     (HsExpr id)
862 \end{code}
863
864 \begin{code}
865 instance OutputableBndr id => Outputable (ArithSeqInfo id) where
866     ppr (From e1)               = hcat [ppr e1, pp_dotdot]
867     ppr (FromThen e1 e2)        = hcat [ppr e1, comma, space, ppr e2, pp_dotdot]
868     ppr (FromTo e1 e3)  = hcat [ppr e1, pp_dotdot, ppr e3]
869     ppr (FromThenTo e1 e2 e3)
870       = hcat [ppr e1, comma, space, ppr e2, pp_dotdot, ppr e3]
871
872 pp_dotdot = ptext SLIT(" .. ")
873 \end{code}
874
875
876 %************************************************************************
877 %*                                                                      *
878 \subsection{HsMatchCtxt}
879 %*                                                                      *
880 %************************************************************************
881
882 \begin{code}
883 data HsMatchContext id  -- Context of a Match
884   = FunRhs id                   -- Function binding for f
885   | CaseAlt                     -- Guard on a case alternative
886   | LambdaExpr                  -- Pattern of a lambda
887   | ProcExpr                    -- Pattern of a proc
888   | PatBindRhs                  -- Pattern binding
889   | RecUpd                      -- Record update [used only in DsExpr to tell matchWrapper
890                                 --      what sort of runtime error message to generate]
891   | StmtCtxt (HsStmtContext id) -- Pattern of a do-stmt or list comprehension
892   deriving ()
893
894 data HsStmtContext id
895   = ListComp 
896   | DoExpr 
897   | MDoExpr                             -- Recursive do-expression
898   | PArrComp                            -- Parallel array comprehension
899   | PatGuard (HsMatchContext id)        -- Pattern guard for specified thing
900   | ParStmtCtxt (HsStmtContext id)      -- A branch of a parallel stmt 
901 \end{code}
902
903 \begin{code}
904 isDoExpr :: HsStmtContext id -> Bool
905 isDoExpr DoExpr  = True
906 isDoExpr MDoExpr = True
907 isDoExpr other   = False
908 \end{code}
909
910 \begin{code}
911 matchSeparator (FunRhs _)   = ptext SLIT("=")
912 matchSeparator CaseAlt      = ptext SLIT("->") 
913 matchSeparator LambdaExpr   = ptext SLIT("->") 
914 matchSeparator ProcExpr     = ptext SLIT("->") 
915 matchSeparator PatBindRhs   = ptext SLIT("=") 
916 matchSeparator (StmtCtxt _) = ptext SLIT("<-")  
917 matchSeparator RecUpd       = panic "unused"
918 \end{code}
919
920 \begin{code}
921 pprMatchContext (FunRhs fun)      = ptext SLIT("the definition of") <+> quotes (ppr fun)
922 pprMatchContext CaseAlt           = ptext SLIT("a case alternative")
923 pprMatchContext RecUpd            = ptext SLIT("a record-update construct")
924 pprMatchContext PatBindRhs        = ptext SLIT("a pattern binding")
925 pprMatchContext LambdaExpr        = ptext SLIT("a lambda abstraction")
926 pprMatchContext ProcExpr          = ptext SLIT("an arrow abstraction")
927 pprMatchContext (StmtCtxt ctxt)   = ptext SLIT("a pattern binding in") $$ pprStmtContext ctxt
928
929 pprMatchRhsContext (FunRhs fun) = ptext SLIT("a right-hand side of function") <+> quotes (ppr fun)
930 pprMatchRhsContext CaseAlt      = ptext SLIT("the body of a case alternative")
931 pprMatchRhsContext PatBindRhs   = ptext SLIT("the right-hand side of a pattern binding")
932 pprMatchRhsContext LambdaExpr   = ptext SLIT("the body of a lambda")
933 pprMatchRhsContext ProcExpr     = ptext SLIT("the body of a proc")
934 pprMatchRhsContext RecUpd       = panic "pprMatchRhsContext"
935
936 pprStmtContext (ParStmtCtxt c) = sep [ptext SLIT("a parallel branch of"), pprStmtContext c]
937 pprStmtContext (PatGuard ctxt) = ptext SLIT("a pattern guard for") $$ pprMatchContext ctxt
938 pprStmtContext DoExpr          = ptext SLIT("a 'do' expression")
939 pprStmtContext MDoExpr         = ptext SLIT("an 'mdo' expression")
940 pprStmtContext ListComp        = ptext SLIT("a list comprehension")
941 pprStmtContext PArrComp        = ptext SLIT("an array comprehension")
942
943 -- Used for the result statement of comprehension
944 -- e.g. the 'e' in      [ e | ... ]
945 --      or the 'r' in   f x = r
946 pprStmtResultContext (PatGuard ctxt) = pprMatchRhsContext ctxt
947 pprStmtResultContext other           = ptext SLIT("the result of") <+> pprStmtContext other
948
949
950 -- Used to generate the string for a *runtime* error message
951 matchContextErrString (FunRhs fun)               = "function " ++ showSDoc (ppr fun)
952 matchContextErrString CaseAlt                    = "case"
953 matchContextErrString PatBindRhs                 = "pattern binding"
954 matchContextErrString RecUpd                     = "record update"
955 matchContextErrString LambdaExpr                 = "lambda"
956 matchContextErrString ProcExpr                   = "proc"
957 matchContextErrString (StmtCtxt (ParStmtCtxt c)) = matchContextErrString (StmtCtxt c)
958 matchContextErrString (StmtCtxt (PatGuard _))    = "pattern guard"
959 matchContextErrString (StmtCtxt DoExpr)          = "'do' expression"
960 matchContextErrString (StmtCtxt MDoExpr)         = "'mdo' expression"
961 matchContextErrString (StmtCtxt ListComp)        = "list comprehension"
962 matchContextErrString (StmtCtxt PArrComp)        = "array comprehension"
963 \end{code}