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