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