d34d4b9a456b1638850de8cd78f006764501c426
[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 <> ptext SLIT("|)"))
451          4 (sep (map pprCmdArg args))
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   | HsLam       (Match  id)     -- kappa
513
514   -- the renamer turns this one into HsArrForm
515   | OpApp       (HsExpr id)     -- left operand
516                 (HsCmd id)      -- operator
517                 Fixity          -- Renamer adds fixity; bottom until then
518                 (HsCmd id)      -- right operand
519
520   | HsPar       (HsCmd id)      -- parenthesised command
521
522   | HsCase      (HsExpr id)
523                 [Match id]      -- bodies are HsCmd's
524                 SrcLoc
525
526   | HsIf        (HsExpr id)     --  predicate
527                 (HsCmd id)      --  then part
528                 (HsCmd id)      --  else part
529                 SrcLoc
530
531   | HsLet       (HsBinds id)    -- let(rec)
532                 (HsCmd  id)
533
534   | HsDo        (HsStmtContext Name)    -- The parameterisation is unimportant
535                                         -- because in this context we never use
536                                         -- the PatGuard or ParStmt variant
537                 [Stmt id]       -- HsExpr's are really HsCmd's
538                 (ReboundNames id)
539                 PostTcType      -- Type of the whole expression
540                 SrcLoc
541
542 Top-level command, introducing a new arrow.
543 This may occur inside a proc (where the stack is empty) or as an
544 argument of a command-forming operator.
545
546 \begin{code}
547 data HsCmdTop id
548   = HsCmdTop    (HsCmd id)
549                 [PostTcType]    -- types of inputs on the command's stack
550                 PostTcType      -- return type of the command
551                 (ReboundNames id)
552                                 -- after type checking:
553                                 -- names used in the command's desugaring
554 \end{code}
555
556 %************************************************************************
557 %*                                                                      *
558 \subsection{Record binds}
559 %*                                                                      *
560 %************************************************************************
561
562 \begin{code}
563 type HsRecordBinds id = [(id, HsExpr id)]
564
565 recBindFields :: HsRecordBinds id -> [id]
566 recBindFields rbinds = [field | (field,_) <- rbinds]
567
568 pp_rbinds :: OutputableBndr id => SDoc -> HsRecordBinds id -> SDoc
569
570 pp_rbinds thing rbinds
571   = hang thing 
572          4 (braces (sep (punctuate comma (map (pp_rbind) rbinds))))
573   where
574     pp_rbind (v, e) = hsep [pprBndr LetBind v, char '=', ppr e]
575 \end{code}
576
577
578
579 %************************************************************************
580 %*                                                                      *
581 \subsection{@Match@, @GRHSs@, and @GRHS@ datatypes}
582 %*                                                                      *
583 %************************************************************************
584
585 @Match@es are sets of pattern bindings and right hand sides for
586 functions, patterns or case branches. For example, if a function @g@
587 is defined as:
588 \begin{verbatim}
589 g (x,y) = y
590 g ((x:ys),y) = y+1,
591 \end{verbatim}
592 then \tr{g} has two @Match@es: @(x,y) = y@ and @((x:ys),y) = y+1@.
593
594 It is always the case that each element of an @[Match]@ list has the
595 same number of @pats@s inside it.  This corresponds to saying that
596 a function defined by pattern matching must have the same number of
597 patterns in each equation.
598
599 \begin{code}
600 data Match id
601   = Match
602         [Pat id]                -- The patterns
603         (Maybe (HsType id))     -- A type signature for the result of the match
604                                 --      Nothing after typechecking
605
606         (GRHSs id)
607
608 -- GRHSs are used both for pattern bindings and for Matches
609 data GRHSs id   
610   = GRHSs [GRHS id]             -- Guarded RHSs
611           (HsBinds id)          -- The where clause
612           PostTcType            -- Type of RHS (after type checking)
613
614 data GRHS id
615   = GRHS  [Stmt id]             -- The RHS is the final ResultStmt
616           SrcLoc
617
618 mkSimpleMatch :: [Pat id] -> HsExpr id -> Type -> SrcLoc -> Match id
619 mkSimpleMatch pats rhs rhs_ty locn
620   = Match pats Nothing (GRHSs (unguardedRHS rhs locn) EmptyBinds rhs_ty)
621
622 unguardedRHS :: HsExpr id -> SrcLoc -> [GRHS id]
623 unguardedRHS rhs loc = [GRHS [ResultStmt rhs loc] loc]
624
625 glueBindsOnGRHSs :: HsBinds id -> GRHSs id -> GRHSs id
626 glueBindsOnGRHSs EmptyBinds grhss = grhss
627 glueBindsOnGRHSs binds1 (GRHSs grhss binds2 ty)
628   = GRHSs grhss (binds1 `ThenBinds` binds2) ty
629 \end{code}
630
631 @getMatchLoc@ takes a @Match@ and returns the
632 source-location gotten from the GRHS inside.
633 THis is something of a nuisance, but no more.
634
635 \begin{code}
636 getMatchLoc :: Match id -> SrcLoc
637 getMatchLoc (Match _ _ (GRHSs (GRHS _ loc : _) _ _)) = loc
638 \end{code}
639
640 We know the list must have at least one @Match@ in it.
641
642 \begin{code}
643 pprMatches :: (OutputableBndr id) => HsMatchContext id -> [Match id] -> SDoc
644 pprMatches ctxt matches = vcat (map (pprMatch ctxt) matches)
645
646 -- Exported to HsBinds, which can't see the defn of HsMatchContext
647 pprFunBind :: (OutputableBndr id) => id -> [Match id] -> SDoc
648 pprFunBind fun matches = pprMatches (FunRhs fun) matches
649
650 -- Exported to HsBinds, which can't see the defn of HsMatchContext
651 pprPatBind :: (OutputableBndr id)
652            => Pat id -> GRHSs id -> SDoc
653 pprPatBind pat grhss = sep [ppr pat, nest 4 (pprGRHSs PatBindRhs grhss)]
654
655
656 pprMatch :: OutputableBndr id => HsMatchContext id -> Match id -> SDoc
657 pprMatch ctxt (Match pats maybe_ty grhss)
658   = pp_name ctxt <+> sep [sep (map ppr pats), 
659                      ppr_maybe_ty,
660                      nest 2 (pprGRHSs ctxt grhss)]
661   where
662     pp_name (FunRhs fun) = ppr fun      -- Not pprBndr; the AbsBinds will
663                                         -- have printed the signature
664     pp_name LambdaExpr   = char '\\'
665     pp_name other        = empty
666
667     ppr_maybe_ty = case maybe_ty of
668                         Just ty -> dcolon <+> ppr ty
669                         Nothing -> empty
670
671
672 pprGRHSs :: OutputableBndr id => HsMatchContext id -> GRHSs id -> SDoc
673 pprGRHSs ctxt (GRHSs grhss binds ty)
674   = vcat (map (pprGRHS ctxt) grhss)
675     $$
676     (if nullBinds binds then empty
677      else text "where" $$ nest 4 (pprDeeper (ppr binds)))
678
679
680 pprGRHS :: OutputableBndr id => HsMatchContext id -> GRHS id -> SDoc
681
682 pprGRHS ctxt (GRHS [ResultStmt expr _] locn)
683  =  pp_rhs ctxt expr
684
685 pprGRHS ctxt (GRHS guarded locn)
686  = sep [char '|' <+> interpp'SP guards, pp_rhs ctxt expr]
687  where
688     ResultStmt expr _ = last guarded    -- Last stmt should be a ResultStmt for guards
689     guards            = init guarded
690
691 pp_rhs ctxt rhs = matchSeparator ctxt <+> pprDeeper (ppr rhs)
692 \end{code}
693
694
695
696 %************************************************************************
697 %*                                                                      *
698 \subsection{Do stmts and list comprehensions}
699 %*                                                                      *
700 %************************************************************************
701
702 \begin{code}
703 data Stmt id
704   = BindStmt    (Pat id) (HsExpr id) SrcLoc
705   | LetStmt     (HsBinds id)
706   | ResultStmt  (HsExpr id)     SrcLoc                  -- See notes that follow
707   | ExprStmt    (HsExpr id)     PostTcType SrcLoc       -- See notes that follow
708         -- The type is the *element type* of the expression
709
710         -- ParStmts only occur in a list comprehension
711   | ParStmt     [([Stmt id], [id])]     -- After remaing, the ids are the binders
712                                         -- bound by the stmts and used subsequently
713
714         -- Recursive statement
715   | RecStmt  [Stmt id] 
716                 --- The next two fields are only valid after renaming
717              [id]       -- The ids are a subset of the variables bound by the stmts
718                         -- that are used in stmts that follow the RecStmt
719
720              [id]       -- Ditto, but these variables are the "recursive" ones, that 
721                         -- are used before they are bound in the stmts of the RecStmt
722                         -- From a type-checking point of view, these ones have to be monomorphic
723
724                 --- This field is only valid after typechecking
725              [HsExpr id]        -- These expressions correspond
726                                 -- 1-to-1 with the "recursive" [id], and are the expresions that 
727                                 -- should be returned by the recursion.  They may not quite be the
728                                 -- Ids themselves, because the Id may be *polymorphic*, but
729                                 -- the returned thing has to be *monomorphic*.
730 \end{code}
731
732 ExprStmts and ResultStmts are a bit tricky, because what they mean
733 depends on the context.  Consider the following contexts:
734
735         A do expression of type (m res_ty)
736         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
737         * ExprStmt E any_ty:   do { ....; E; ... }
738                 E :: m any_ty
739           Translation: E >> ...
740         
741         * ResultStmt E:   do { ....; E }
742                 E :: m res_ty
743           Translation: E
744         
745         A list comprehensions of type [elt_ty]
746         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
747         * ExprStmt E Bool:   [ .. | .... E ]
748                         [ .. | ..., E, ... ]
749                         [ .. | .... | ..., E | ... ]
750                 E :: Bool
751           Translation: if E then fail else ...
752
753         * ResultStmt E:   [ E | ... ]
754                 E :: elt_ty
755           Translation: return E
756         
757         A guard list, guarding a RHS of type rhs_ty
758         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
759         * ExprStmt E Bool:   f x | ..., E, ... = ...rhs...
760                 E :: Bool
761           Translation: if E then fail else ...
762         
763         * ResultStmt E:   f x | ...guards... = E
764                 E :: rhs_ty
765           Translation: E
766
767 Array comprehensions are handled like list comprehensions -=chak
768
769 \begin{code}
770 consLetStmt :: HsBinds id -> [Stmt id] -> [Stmt id]
771 consLetStmt EmptyBinds stmts = stmts
772 consLetStmt binds      stmts = LetStmt binds : stmts
773 \end{code}
774
775 \begin{code}
776 instance OutputableBndr id => Outputable (Stmt id) where
777     ppr stmt = pprStmt stmt
778
779 pprStmt (BindStmt pat expr _)   = hsep [ppr pat, ptext SLIT("<-"), ppr expr]
780 pprStmt (LetStmt binds)         = hsep [ptext SLIT("let"), pprBinds binds]
781 pprStmt (ExprStmt expr _ _)     = ppr expr
782 pprStmt (ResultStmt expr _)     = ppr expr
783 pprStmt (ParStmt stmtss)        = hsep (map (\stmts -> ptext SLIT("| ") <> ppr stmts) stmtss)
784 pprStmt (RecStmt segment _ _ _) = ptext SLIT("rec") <+> braces (vcat (map ppr segment))
785
786 pprDo :: OutputableBndr id => HsStmtContext any -> [Stmt id] -> SDoc
787 pprDo DoExpr stmts   = hang (ptext SLIT("do")) 2 (vcat (map ppr stmts))
788 pprDo MDoExpr stmts  = hang (ptext SLIT("mdo")) 3 (vcat (map ppr stmts))
789 pprDo ListComp stmts = pprComp brackets   stmts
790 pprDo PArrComp stmts = pprComp pa_brackets stmts
791
792 pprComp :: OutputableBndr id => (SDoc -> SDoc) -> [Stmt id] -> SDoc
793 pprComp brack stmts = brack $
794                       hang (pprExpr expr <+> char '|')
795                          4 (interpp'SP quals)
796                     where
797                       ResultStmt expr _ = last stmts  -- Last stmt should
798                       quals             = init stmts  -- be an ResultStmt
799 \end{code}
800
801 %************************************************************************
802 %*                                                                      *
803                 Template Haskell quotation brackets
804 %*                                                                      *
805 %************************************************************************
806
807 \begin{code}
808 data HsBracket id = ExpBr (HsExpr id)
809                   | PatBr (Pat id)
810                   | DecBr (HsGroup id)
811                   | TypBr (HsType id)
812
813 instance OutputableBndr id => Outputable (HsBracket id) where
814   ppr = pprHsBracket
815
816
817 pprHsBracket (ExpBr e) = thBrackets empty (ppr e)
818 pprHsBracket (PatBr p) = thBrackets (char 'p') (ppr p)
819 pprHsBracket (DecBr d) = thBrackets (char 'd') (ppr d)
820 pprHsBracket (TypBr t) = thBrackets (char 't') (ppr t)
821
822
823 thBrackets pp_kind pp_body = char '[' <> pp_kind <> char '|' <+> 
824                              pp_body <+> ptext SLIT("|]")
825
826 data HsReify id = Reify    ReifyFlavour id      -- Pre typechecking
827                 | ReifyOut ReifyFlavour Name    -- Post typechecking
828                                                 -- The Name could be the name of
829                                                 -- an Id, TyCon, or Class
830
831 data ReifyFlavour = ReifyDecl | ReifyType | ReifyFixity
832
833 instance Outputable id => Outputable (HsReify id) where
834    ppr (Reify flavour id) = ppr flavour <+> ppr id
835    ppr (ReifyOut flavour thing) = ppr flavour <+> ppr thing
836
837 instance Outputable ReifyFlavour where
838    ppr ReifyDecl   = ptext SLIT("reifyDecl")
839    ppr ReifyType   = ptext SLIT("reifyType")
840    ppr ReifyFixity = ptext SLIT("reifyFixity")
841 \end{code}
842
843 %************************************************************************
844 %*                                                                      *
845 \subsection{Enumerations and list comprehensions}
846 %*                                                                      *
847 %************************************************************************
848
849 \begin{code}
850 data ArithSeqInfo id
851   = From            (HsExpr id)
852   | FromThen        (HsExpr id)
853                     (HsExpr id)
854   | FromTo          (HsExpr id)
855                     (HsExpr id)
856   | FromThenTo      (HsExpr id)
857                     (HsExpr id)
858                     (HsExpr id)
859 \end{code}
860
861 \begin{code}
862 instance OutputableBndr id => Outputable (ArithSeqInfo id) where
863     ppr (From e1)               = hcat [ppr e1, pp_dotdot]
864     ppr (FromThen e1 e2)        = hcat [ppr e1, comma, space, ppr e2, pp_dotdot]
865     ppr (FromTo e1 e3)  = hcat [ppr e1, pp_dotdot, ppr e3]
866     ppr (FromThenTo e1 e2 e3)
867       = hcat [ppr e1, comma, space, ppr e2, pp_dotdot, ppr e3]
868
869 pp_dotdot = ptext SLIT(" .. ")
870 \end{code}
871
872
873 %************************************************************************
874 %*                                                                      *
875 \subsection{HsMatchCtxt}
876 %*                                                                      *
877 %************************************************************************
878
879 \begin{code}
880 data HsMatchContext id  -- Context of a Match
881   = FunRhs id                   -- Function binding for f
882   | CaseAlt                     -- Guard on a case alternative
883   | LambdaExpr                  -- Pattern of a lambda
884   | ProcExpr                    -- Pattern of a proc
885   | PatBindRhs                  -- Pattern binding
886   | RecUpd                      -- Record update [used only in DsExpr to tell matchWrapper
887                                 --      what sort of runtime error message to generate]
888   | StmtCtxt (HsStmtContext id) -- Pattern of a do-stmt or list comprehension
889   deriving ()
890
891 data HsStmtContext id
892   = ListComp 
893   | DoExpr 
894   | MDoExpr                             -- Recursive do-expression
895   | PArrComp                            -- Parallel array comprehension
896   | PatGuard (HsMatchContext id)        -- Pattern guard for specified thing
897   | ParStmtCtxt (HsStmtContext id)      -- A branch of a parallel stmt 
898 \end{code}
899
900 \begin{code}
901 isDoExpr :: HsStmtContext id -> Bool
902 isDoExpr DoExpr  = True
903 isDoExpr MDoExpr = True
904 isDoExpr other   = False
905 \end{code}
906
907 \begin{code}
908 matchSeparator (FunRhs _)   = ptext SLIT("=")
909 matchSeparator CaseAlt      = ptext SLIT("->") 
910 matchSeparator LambdaExpr   = ptext SLIT("->") 
911 matchSeparator ProcExpr     = ptext SLIT("->") 
912 matchSeparator PatBindRhs   = ptext SLIT("=") 
913 matchSeparator (StmtCtxt _) = ptext SLIT("<-")  
914 matchSeparator RecUpd       = panic "unused"
915 \end{code}
916
917 \begin{code}
918 pprMatchContext (FunRhs fun)      = ptext SLIT("the definition of") <+> quotes (ppr fun)
919 pprMatchContext CaseAlt           = ptext SLIT("a case alternative")
920 pprMatchContext RecUpd            = ptext SLIT("a record-update construct")
921 pprMatchContext PatBindRhs        = ptext SLIT("a pattern binding")
922 pprMatchContext LambdaExpr        = ptext SLIT("a lambda abstraction")
923 pprMatchContext ProcExpr          = ptext SLIT("an arrow abstraction")
924 pprMatchContext (StmtCtxt ctxt)   = ptext SLIT("a pattern binding in") $$ pprStmtContext ctxt
925
926 pprMatchRhsContext (FunRhs fun) = ptext SLIT("a right-hand side of function") <+> quotes (ppr fun)
927 pprMatchRhsContext CaseAlt      = ptext SLIT("the body of a case alternative")
928 pprMatchRhsContext PatBindRhs   = ptext SLIT("the right-hand side of a pattern binding")
929 pprMatchRhsContext LambdaExpr   = ptext SLIT("the body of a lambda")
930 pprMatchRhsContext ProcExpr     = ptext SLIT("the body of a proc")
931 pprMatchRhsContext RecUpd       = panic "pprMatchRhsContext"
932
933 pprStmtContext (ParStmtCtxt c) = sep [ptext SLIT("a parallel branch of"), pprStmtContext c]
934 pprStmtContext (PatGuard ctxt) = ptext SLIT("a pattern guard for") $$ pprMatchContext ctxt
935 pprStmtContext DoExpr          = ptext SLIT("a 'do' expression")
936 pprStmtContext MDoExpr         = ptext SLIT("an 'mdo' expression")
937 pprStmtContext ListComp        = ptext SLIT("a list comprehension")
938 pprStmtContext PArrComp        = ptext SLIT("an array comprehension")
939
940 -- Used for the result statement of comprehension
941 -- e.g. the 'e' in      [ e | ... ]
942 --      or the 'r' in   f x = r
943 pprStmtResultContext (PatGuard ctxt) = pprMatchRhsContext ctxt
944 pprStmtResultContext other           = ptext SLIT("the result of") <+> pprStmtContext other
945
946
947 -- Used to generate the string for a *runtime* error message
948 matchContextErrString (FunRhs fun)               = "function " ++ showSDoc (ppr fun)
949 matchContextErrString CaseAlt                    = "case"
950 matchContextErrString PatBindRhs                 = "pattern binding"
951 matchContextErrString RecUpd                     = "record update"
952 matchContextErrString LambdaExpr                 = "lambda"
953 matchContextErrString ProcExpr                   = "proc"
954 matchContextErrString (StmtCtxt (ParStmtCtxt c)) = matchContextErrString (StmtCtxt c)
955 matchContextErrString (StmtCtxt (PatGuard _))    = "pattern guard"
956 matchContextErrString (StmtCtxt DoExpr)          = "'do' expression"
957 matchContextErrString (StmtCtxt MDoExpr)         = "'mdo' expression"
958 matchContextErrString (StmtCtxt ListComp)        = "list comprehension"
959 matchContextErrString (StmtCtxt PArrComp)        = "array comprehension"
960 \end{code}