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