c2e4c8adbd3a529d1bba1ce0a8e15feacb354918
[ghc-hetmet.git] / compiler / hsSyn / HsExpr.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5
6 HsExpr: Abstract Haskell syntax: expressions
7
8 \begin{code}
9 {-# OPTIONS -w #-}
10 -- The above warning supression flag is a temporary kludge.
11 -- While working on this module you are encouraged to remove it and fix
12 -- any warnings in the module. See
13 --     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
14 -- for details
15
16 module HsExpr where
17
18 #include "HsVersions.h"
19
20 -- friends:
21 import HsDecls
22 import HsPat
23 import HsLit
24 import HsTypes
25 import HsImpExp
26 import HsBinds
27
28 -- others:
29 import Var
30 import Name
31 import BasicTypes
32 import DataCon
33 import SrcLoc
34 import Outputable       
35 import FastString
36 \end{code}
37
38
39 %************************************************************************
40 %*                                                                      *
41 \subsection{Expressions proper}
42 %*                                                                      *
43 %************************************************************************
44
45 \begin{code}
46 type LHsExpr id = Located (HsExpr id)
47
48 -------------------------
49 -- PostTcExpr is an evidence expression attached to the
50 -- syntax tree by the type checker (c.f. postTcType)
51 -- We use a PostTcTable where there are a bunch of pieces of 
52 -- evidence, more than is convenient to keep individually
53 type PostTcExpr  = HsExpr Id
54 type PostTcTable = [(Name, Id)]
55
56 noPostTcExpr :: PostTcExpr
57 noPostTcExpr = HsLit (HsString FSLIT("noPostTcExpr"))
58
59 noPostTcTable :: PostTcTable
60 noPostTcTable = []
61
62 -------------------------
63 -- SyntaxExpr is like PostTcExpr, but it's filled in a little earlier,
64 -- by the renamer.  It's used for rebindable syntax.  
65 -- E.g. (>>=) is filled in before the renamer by the appropriate Name
66 --      for (>>=), and then instantiated by the type checker with its
67 --      type args tec
68
69 type SyntaxExpr id = HsExpr id
70
71 noSyntaxExpr :: SyntaxExpr id   -- Before renaming, and sometimes after,
72                                 -- (if the syntax slot makes no sense)
73 noSyntaxExpr = HsLit (HsString FSLIT("noSyntaxExpr"))
74
75
76 type SyntaxTable id = [(Name, SyntaxExpr id)]
77 --      *** Currently used only for CmdTop (sigh) ***
78 -- * Before the renamer, this list is noSyntaxTable
79 --
80 -- * After the renamer, it takes the form [(std_name, HsVar actual_name)]
81 --   For example, for the 'return' op of a monad
82 --      normal case:            (GHC.Base.return, HsVar GHC.Base.return)
83 --      with rebindable syntax: (GHC.Base.return, return_22)
84 --              where return_22 is whatever "return" is in scope
85 --
86 -- * After the type checker, it takes the form [(std_name, <expression>)]
87 --      where <expression> is the evidence for the method
88
89 noSyntaxTable :: SyntaxTable id
90 noSyntaxTable = []
91
92
93 -------------------------
94 data HsExpr id
95   = HsVar       id              -- variable
96   | HsIPVar     (IPName id)     -- implicit parameter
97   | HsOverLit   (HsOverLit id) -- Overloaded literals
98
99   | HsLit       HsLit           -- Simple (non-overloaded) literals
100
101   | HsLam       (MatchGroup  id)        -- Currently always a single match
102
103   | HsApp       (LHsExpr id)            -- Application
104                 (LHsExpr id)
105
106   -- Operator applications:
107   -- NB Bracketed ops such as (+) come out as Vars.
108
109   -- NB We need an expr for the operator in an OpApp/Section since
110   -- the typechecker may need to apply the operator to a few types.
111
112   | OpApp       (LHsExpr id)    -- left operand
113                 (LHsExpr id)    -- operator
114                 Fixity          -- Renamer adds fixity; bottom until then
115                 (LHsExpr id)    -- right operand
116
117   | NegApp      (LHsExpr id)    -- negated expr
118                 (SyntaxExpr id) -- Name of 'negate'
119
120   | HsPar       (LHsExpr id)    -- parenthesised expr
121
122   | SectionL    (LHsExpr id)    -- operand
123                 (LHsExpr id)    -- operator
124   | SectionR    (LHsExpr id)    -- operator
125                 (LHsExpr id)    -- operand
126                                 
127   | HsCase      (LHsExpr id)
128                 (MatchGroup id)
129
130   | HsIf        (LHsExpr id)    --  predicate
131                 (LHsExpr id)    --  then part
132                 (LHsExpr id)    --  else part
133
134   | HsLet       (HsLocalBinds id) -- let(rec)
135                 (LHsExpr  id)
136
137   | HsDo        (HsStmtContext Name)    -- The parameterisation is unimportant
138                                         -- because in this context we never use
139                                         -- the PatGuard or ParStmt variant
140                 [LStmt id]              -- "do":one or more stmts
141                 (LHsExpr id)            -- The body; the last expression in the 'do'
142                                         --           of [ body | ... ] in a list comp
143                 PostTcType              -- Type of the whole expression
144
145   | ExplicitList                -- syntactic list
146                 PostTcType      -- Gives type of components of list
147                 [LHsExpr id]
148
149   | ExplicitPArr                -- syntactic parallel array: [:e1, ..., en:]
150                 PostTcType      -- type of elements of the parallel array
151                 [LHsExpr id]
152
153   | ExplicitTuple               -- tuple
154                 [LHsExpr id]
155                                 -- NB: Unit is ExplicitTuple []
156                                 -- for tuples, we can get the types
157                                 -- direct from the components
158                 Boxity
159
160
161         -- Record construction
162   | RecordCon   (Located id)            -- The constructor.  After type checking
163                                         -- it's the dataConWrapId of the constructor
164                 PostTcExpr              -- Data con Id applied to type args
165                 (HsRecordBinds id)
166
167         -- Record update
168   | RecordUpd   (LHsExpr id)
169                 (HsRecordBinds id)
170                 [DataCon]               -- Filled in by the type checker to the *non-empty*
171                                         -- list of DataCons that have all the upd'd fields
172                 [PostTcType]            -- Argument types of *input* record type
173                 [PostTcType]            --              and  *output* record type
174         -- For a type family, the arg types are of the *instance* tycon, not the family tycon
175
176   | ExprWithTySig                       -- e :: type
177                 (LHsExpr id)
178                 (LHsType id)
179
180   | ExprWithTySigOut                    -- TRANSLATION
181                 (LHsExpr id)
182                 (LHsType Name)          -- Retain the signature for round-tripping purposes
183
184   | ArithSeq                            -- arithmetic sequence
185                 PostTcExpr
186                 (ArithSeqInfo id)
187
188   | PArrSeq                             -- arith. sequence for parallel array
189                 PostTcExpr              -- [:e1..e2:] or [:e1, e2..e3:]
190                 (ArithSeqInfo id)
191
192   | HsSCC       FastString      -- "set cost centre" (_scc_) annotation
193                 (LHsExpr id)    -- expr whose cost is to be measured
194
195   | HsCoreAnn   FastString      -- hdaume: core annotation
196                 (LHsExpr id)
197                 
198   -----------------------------------------------------------
199   -- MetaHaskell Extensions
200
201   | HsBracket    (HsBracket id)
202
203   | HsBracketOut (HsBracket Name)       -- Output of the type checker is the *original*
204                  [PendingSplice]        -- renamed expression, plus *typechecked* splices
205                                         -- to be pasted back in by the desugarer
206
207   | HsSpliceE (HsSplice id) 
208
209   -----------------------------------------------------------
210   -- Arrow notation extension
211
212   | HsProc      (LPat id)               -- arrow abstraction, proc
213                 (LHsCmdTop id)          -- body of the abstraction
214                                         -- always has an empty stack
215
216   ---------------------------------------
217   -- The following are commands, not expressions proper
218
219   | HsArrApp    -- Arrow tail, or arrow application (f -< arg)
220         (LHsExpr id)    -- arrow expression, f
221         (LHsExpr id)    -- input expression, arg
222         PostTcType      -- type of the arrow expressions f,
223                         -- of the form a t t', where arg :: t
224         HsArrAppType    -- higher-order (-<<) or first-order (-<)
225         Bool            -- True => right-to-left (f -< arg)
226                         -- False => left-to-right (arg >- f)
227
228   | HsArrForm   -- Command formation,  (| e cmd1 .. cmdn |)
229         (LHsExpr id)    -- the operator
230                         -- after type-checking, a type abstraction to be
231                         -- applied to the type of the local environment tuple
232         (Maybe Fixity)  -- fixity (filled in by the renamer), for forms that
233                         -- were converted from OpApp's by the renamer
234         [LHsCmdTop id]  -- argument commands
235
236
237   ---------------------------------------
238   -- Haskell program coverage (Hpc) Support
239
240   | HsTick 
241      Int                                -- module-local tick number
242      [id]                               -- variables in scope
243      (LHsExpr id)                       -- sub-expression
244
245   | HsBinTick
246      Int                                -- module-local tick number for True
247      Int                                -- module-local tick number for False
248      (LHsExpr id)                       -- sub-expression
249
250   | HsTickPragma                        -- A pragma introduced tick
251      (FastString,(Int,Int),(Int,Int))   -- external span for this tick    
252      (LHsExpr id)     
253
254   ---------------------------------------
255   -- These constructors only appear temporarily in the parser.
256   -- The renamer translates them into the Right Thing.
257
258   | EWildPat                    -- wildcard
259
260   | EAsPat      (Located id)    -- as pattern
261                 (LHsExpr id)
262
263   | EViewPat    (LHsExpr id)    -- view pattern
264                 (LHsExpr id)
265
266   | ELazyPat    (LHsExpr id) -- ~ pattern
267
268   | HsType      (LHsType id)     -- Explicit type argument; e.g  f {| Int |} x y
269
270   ---------------------------------------
271   -- Finally, HsWrap appears only in typechecker output
272
273   |  HsWrap     HsWrapper       -- TRANSLATION
274                 (HsExpr id)
275
276 type PendingSplice = (Name, LHsExpr Id) -- Typechecked splices, waiting to be 
277                                         -- pasted back in by the desugarer
278 \end{code}
279
280 A @Dictionary@, unless of length 0 or 1, becomes a tuple.  A
281 @ClassDictLam dictvars methods expr@ is, therefore:
282 \begin{verbatim}
283 \ x -> case x of ( dictvars-and-methods-tuple ) -> expr
284 \end{verbatim}
285
286 \begin{code}
287 instance OutputableBndr id => Outputable (HsExpr id) where
288     ppr expr = pprExpr expr
289 \end{code}
290
291 \begin{code}
292 -----------------------
293 -- pprExpr, pprLExpr, pprBinds call pprDeeper; 
294 -- the underscore versions do not
295 pprLExpr :: OutputableBndr id => LHsExpr id -> SDoc
296 pprLExpr (L _ e) = pprExpr e
297
298 pprExpr :: OutputableBndr id => HsExpr id -> SDoc
299 pprExpr e | isAtomicHsExpr e || isQuietHsExpr e =            ppr_expr e
300           | otherwise                           = pprDeeper (ppr_expr e)
301
302 isQuietHsExpr :: HsExpr id -> Bool
303 -- Parentheses do display something, but it gives little info and
304 -- if we go deeper when we go inside them then we get ugly things
305 -- like (...)
306 isQuietHsExpr (HsPar _) = True
307 -- applications don't display anything themselves
308 isQuietHsExpr (HsApp _ _) = True
309 isQuietHsExpr (OpApp _ _ _ _) = True
310 isQuietHsExpr _ = False
311
312 pprBinds :: (OutputableBndr idL, OutputableBndr idR) => HsLocalBindsLR idL idR -> SDoc
313 pprBinds b = pprDeeper (ppr b)
314
315 -----------------------
316 ppr_lexpr :: OutputableBndr id => LHsExpr id -> SDoc
317 ppr_lexpr e = ppr_expr (unLoc e)
318
319 ppr_expr :: OutputableBndr id => HsExpr id -> SDoc
320 ppr_expr (HsVar v)       = pprHsVar v
321 ppr_expr (HsIPVar v)     = ppr v
322 ppr_expr (HsLit lit)     = ppr lit
323 ppr_expr (HsOverLit lit) = ppr lit
324 ppr_expr (HsPar e)       = parens (ppr_lexpr e)
325
326 ppr_expr (HsCoreAnn s e)
327   = vcat [ptext SLIT("HsCoreAnn") <+> ftext s, ppr_lexpr e]
328
329 ppr_expr (HsApp e1 e2)
330   = let (fun, args) = collect_args e1 [e2] in
331     hang (ppr_lexpr fun) 2 (sep (map pprParendExpr args))
332   where
333     collect_args (L _ (HsApp fun arg)) args = collect_args fun (arg:args)
334     collect_args fun args = (fun, args)
335
336 ppr_expr (OpApp e1 op fixity e2)
337   = case unLoc op of
338       HsVar v -> pp_infixly v
339       _       -> pp_prefixly
340   where
341     pp_e1 = pprDebugParendExpr e1   -- In debug mode, add parens 
342     pp_e2 = pprDebugParendExpr e2   -- to make precedence clear
343
344     pp_prefixly
345       = hang (ppr op) 2 (sep [pp_e1, pp_e2])
346
347     pp_infixly v
348       = sep [nest 2 pp_e1, pprInfix v, nest 2 pp_e2]
349
350 ppr_expr (NegApp e _) = char '-' <+> pprDebugParendExpr e
351
352 ppr_expr (SectionL expr op)
353   = case unLoc op of
354       HsVar v -> pp_infixly v
355       _       -> pp_prefixly
356   where
357     pp_expr = pprDebugParendExpr expr
358
359     pp_prefixly = hang (hsep [text " \\ x_ ->", ppr op])
360                        4 (hsep [pp_expr, ptext SLIT("x_ )")])
361     pp_infixly v = (sep [pp_expr, pprInfix v])
362
363 ppr_expr (SectionR op expr)
364   = case unLoc op of
365       HsVar v -> pp_infixly v
366       _       -> pp_prefixly
367   where
368     pp_expr = pprDebugParendExpr expr
369
370     pp_prefixly = hang (hsep [text "( \\ x_ ->", ppr op, ptext SLIT("x_")])
371                        4 ((<>) pp_expr rparen)
372     pp_infixly v
373       = (sep [pprInfix v, pp_expr])
374
375 ppr_expr (HsLam matches :: HsExpr id) 
376   = pprMatches (LambdaExpr :: HsMatchContext id) matches
377
378 ppr_expr (HsCase expr matches :: HsExpr id)
379   = sep [ sep [ptext SLIT("case"), nest 4 (ppr expr), ptext SLIT("of")],
380             nest 2 (pprMatches (CaseAlt :: HsMatchContext id) matches) ]
381
382 ppr_expr (HsIf e1 e2 e3)
383   = sep [hsep [ptext SLIT("if"), nest 2 (ppr e1), ptext SLIT("then")],
384            nest 4 (ppr e2),
385            ptext SLIT("else"),
386            nest 4 (ppr e3)]
387
388 -- special case: let ... in let ...
389 ppr_expr (HsLet binds expr@(L _ (HsLet _ _)))
390   = sep [hang (ptext SLIT("let")) 2 (hsep [pprBinds binds, ptext SLIT("in")]),
391          ppr_lexpr expr]
392
393 ppr_expr (HsLet binds expr)
394   = sep [hang (ptext SLIT("let")) 2 (pprBinds binds),
395          hang (ptext SLIT("in"))  2 (ppr expr)]
396
397 ppr_expr (HsDo do_or_list_comp stmts body _) = pprDo do_or_list_comp stmts body
398
399 ppr_expr (ExplicitList _ exprs)
400   = brackets (pprDeeperList fsep (punctuate comma (map ppr_lexpr exprs)))
401
402 ppr_expr (ExplicitPArr _ exprs)
403   = pa_brackets (pprDeeperList fsep (punctuate comma (map ppr_lexpr exprs)))
404
405 ppr_expr (ExplicitTuple exprs boxity)
406   = tupleParens boxity (sep (punctuate comma (map ppr_lexpr exprs)))
407
408 ppr_expr (RecordCon con_id con_expr rbinds)
409   = hang (ppr con_id) 2 (ppr rbinds)
410
411 ppr_expr (RecordUpd aexp rbinds _ _ _)
412   = hang (pprParendExpr aexp) 2 (ppr rbinds)
413
414 ppr_expr (ExprWithTySig expr sig)
415   = hang (nest 2 (ppr_lexpr expr) <+> dcolon)
416          4 (ppr sig)
417 ppr_expr (ExprWithTySigOut expr sig)
418   = hang (nest 2 (ppr_lexpr expr) <+> dcolon)
419          4 (ppr sig)
420
421 ppr_expr (ArithSeq expr info) = brackets (ppr info)
422 ppr_expr (PArrSeq expr info)  = pa_brackets (ppr info)
423
424 ppr_expr EWildPat     = char '_'
425 ppr_expr (ELazyPat e) = char '~' <> pprParendExpr e
426 ppr_expr (EAsPat v e) = ppr v <> char '@' <> pprParendExpr e
427
428 ppr_expr (HsSCC lbl expr)
429   = sep [ ptext SLIT("_scc_") <+> doubleQuotes (ftext lbl), pprParendExpr expr ]
430
431 ppr_expr (HsWrap co_fn e) = pprHsWrapper (pprExpr e) co_fn
432 ppr_expr (HsType id)        = ppr id
433
434 ppr_expr (HsSpliceE s)       = pprSplice s
435 ppr_expr (HsBracket b)       = pprHsBracket b
436 ppr_expr (HsBracketOut e []) = ppr e    
437 ppr_expr (HsBracketOut e ps) = ppr e $$ ptext SLIT("pending") <+> ppr ps
438
439 ppr_expr (HsProc pat (L _ (HsCmdTop cmd _ _ _)))
440   = hsep [ptext SLIT("proc"), ppr pat, ptext SLIT("->"), ppr cmd]
441
442 ppr_expr (HsTick tickId vars exp)
443   = hcat [ptext SLIT("tick<"), ppr tickId,ptext SLIT(">("), hsep (map pprHsVar vars), ppr exp,ptext SLIT(")")]
444 ppr_expr (HsBinTick tickIdTrue tickIdFalse exp)
445   = hcat [ptext SLIT("bintick<"), 
446           ppr tickIdTrue,
447           ptext SLIT(","),
448           ppr tickIdFalse,
449           ptext SLIT(">("), 
450           ppr exp,ptext SLIT(")")]
451 ppr_expr (HsTickPragma externalSrcLoc exp)
452   = hcat [ptext SLIT("tickpragma<"), ppr externalSrcLoc,ptext SLIT(">("), ppr exp,ptext SLIT(")")]
453
454 ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp True)
455   = hsep [ppr_lexpr arrow, ptext SLIT("-<"), ppr_lexpr arg]
456 ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp False)
457   = hsep [ppr_lexpr arg, ptext SLIT(">-"), ppr_lexpr arrow]
458 ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp True)
459   = hsep [ppr_lexpr arrow, ptext SLIT("-<<"), ppr_lexpr arg]
460 ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp False)
461   = hsep [ppr_lexpr arg, ptext SLIT(">>-"), ppr_lexpr arrow]
462
463 ppr_expr (HsArrForm (L _ (HsVar v)) (Just _) [arg1, arg2])
464   = sep [pprCmdArg (unLoc arg1), hsep [pprInfix v, pprCmdArg (unLoc arg2)]]
465 ppr_expr (HsArrForm op _ args)
466   = hang (ptext SLIT("(|") <> ppr_lexpr op)
467          4 (sep (map (pprCmdArg.unLoc) args) <> ptext SLIT("|)"))
468
469 pprCmdArg :: OutputableBndr id => HsCmdTop id -> SDoc
470 pprCmdArg (HsCmdTop cmd@(L _ (HsArrForm _ Nothing [])) _ _ _)
471   = ppr_lexpr cmd
472 pprCmdArg (HsCmdTop cmd _ _ _)
473   = parens (ppr_lexpr cmd)
474
475 -- Put a var in backquotes if it's not an operator already
476 pprInfix :: Outputable name => name -> SDoc
477 pprInfix v | isOperator ppr_v = ppr_v
478            | otherwise        = char '`' <> ppr_v <> char '`'
479            where
480              ppr_v = ppr v
481
482 -- add parallel array brackets around a document
483 --
484 pa_brackets :: SDoc -> SDoc
485 pa_brackets p = ptext SLIT("[:") <> p <> ptext SLIT(":]")    
486 \end{code}
487
488 HsSyn records exactly where the user put parens, with HsPar.
489 So generally speaking we print without adding any parens.
490 However, some code is internally generated, and in some places
491 parens are absolutely required; so for these places we use
492 pprParendExpr (but don't print double parens of course).
493
494 For operator applications we don't add parens, because the oprerator
495 fixities should do the job, except in debug mode (-dppr-debug) so we
496 can see the structure of the parse tree.
497
498 \begin{code}
499 pprDebugParendExpr :: OutputableBndr id => LHsExpr id -> SDoc
500 pprDebugParendExpr expr
501   = getPprStyle (\sty ->
502     if debugStyle sty then pprParendExpr expr
503                       else pprLExpr      expr)
504   
505 pprParendExpr :: OutputableBndr id => LHsExpr id -> SDoc
506 pprParendExpr expr
507   = let
508         pp_as_was = pprLExpr expr
509         -- Using pprLExpr makes sure that we go 'deeper'
510         -- I think that is usually (always?) right
511     in
512     case unLoc expr of
513       HsLit l              -> pp_as_was
514       HsOverLit l          -> pp_as_was
515       HsVar _              -> pp_as_was
516       HsIPVar _            -> pp_as_was
517       ExplicitList _ _     -> pp_as_was
518       ExplicitPArr _ _     -> pp_as_was
519       ExplicitTuple _ _    -> pp_as_was
520       HsPar _              -> pp_as_was
521       HsBracket _          -> pp_as_was
522       HsBracketOut _ []    -> pp_as_was
523       HsDo sc _ _ _
524        | isListCompExpr sc -> pp_as_was
525       _                    -> parens pp_as_was
526
527 isAtomicHsExpr :: HsExpr id -> Bool     -- A single token
528 isAtomicHsExpr (HsVar {})     = True
529 isAtomicHsExpr (HsLit {})     = True
530 isAtomicHsExpr (HsOverLit {}) = True
531 isAtomicHsExpr (HsIPVar {})   = True
532 isAtomicHsExpr (HsWrap _ e)   = isAtomicHsExpr e
533 isAtomicHsExpr (HsPar e)      = isAtomicHsExpr (unLoc e)
534 isAtomicHsExpr e              = False
535 \end{code}
536
537 %************************************************************************
538 %*                                                                      *
539 \subsection{Commands (in arrow abstractions)}
540 %*                                                                      *
541 %************************************************************************
542
543 We re-use HsExpr to represent these.
544
545 \begin{code}
546 type HsCmd id = HsExpr id
547
548 type LHsCmd id = LHsExpr id
549
550 data HsArrAppType = HsHigherOrderApp | HsFirstOrderApp
551 \end{code}
552
553 The legal constructors for commands are:
554
555   = HsArrApp ...                -- as above
556
557   | HsArrForm ...               -- as above
558
559   | HsApp       (HsCmd id)
560                 (HsExpr id)
561
562   | HsLam       (Match  id)     -- kappa
563
564   -- the renamer turns this one into HsArrForm
565   | OpApp       (HsExpr id)     -- left operand
566                 (HsCmd id)      -- operator
567                 Fixity          -- Renamer adds fixity; bottom until then
568                 (HsCmd id)      -- right operand
569
570   | HsPar       (HsCmd id)      -- parenthesised command
571
572   | HsCase      (HsExpr id)
573                 [Match id]      -- bodies are HsCmd's
574                 SrcLoc
575
576   | HsIf        (HsExpr id)     --  predicate
577                 (HsCmd id)      --  then part
578                 (HsCmd id)      --  else part
579                 SrcLoc
580
581   | HsLet       (HsLocalBinds id)       -- let(rec)
582                 (HsCmd  id)
583
584   | HsDo        (HsStmtContext Name)    -- The parameterisation is unimportant
585                                         -- because in this context we never use
586                                         -- the PatGuard or ParStmt variant
587                 [Stmt id]       -- HsExpr's are really HsCmd's
588                 PostTcType      -- Type of the whole expression
589                 SrcLoc
590
591 Top-level command, introducing a new arrow.
592 This may occur inside a proc (where the stack is empty) or as an
593 argument of a command-forming operator.
594
595 \begin{code}
596 type LHsCmdTop id = Located (HsCmdTop id)
597
598 data HsCmdTop id
599   = HsCmdTop    (LHsCmd id)
600                 [PostTcType]    -- types of inputs on the command's stack
601                 PostTcType      -- return type of the command
602                 (SyntaxTable id)
603                                 -- after type checking:
604                                 -- names used in the command's desugaring
605 \end{code}
606
607 %************************************************************************
608 %*                                                                      *
609 \subsection{Record binds}
610 %*                                                                      *
611 %************************************************************************
612
613 \begin{code}
614 type HsRecordBinds id = HsRecFields id (LHsExpr id)
615 \end{code}
616
617
618
619 %************************************************************************
620 %*                                                                      *
621 \subsection{@Match@, @GRHSs@, and @GRHS@ datatypes}
622 %*                                                                      *
623 %************************************************************************
624
625 @Match@es are sets of pattern bindings and right hand sides for
626 functions, patterns or case branches. For example, if a function @g@
627 is defined as:
628 \begin{verbatim}
629 g (x,y) = y
630 g ((x:ys),y) = y+1,
631 \end{verbatim}
632 then \tr{g} has two @Match@es: @(x,y) = y@ and @((x:ys),y) = y+1@.
633
634 It is always the case that each element of an @[Match]@ list has the
635 same number of @pats@s inside it.  This corresponds to saying that
636 a function defined by pattern matching must have the same number of
637 patterns in each equation.
638
639 \begin{code}
640 data MatchGroup id 
641   = MatchGroup 
642         [LMatch id]     -- The alternatives
643         PostTcType      -- The type is the type of the entire group
644                         --      t1 -> ... -> tn -> tr
645                         -- where there are n patterns
646
647 type LMatch id = Located (Match id)
648
649 data Match id
650   = Match
651         [LPat id]               -- The patterns
652         (Maybe (LHsType id))    -- A type signature for the result of the match
653                                 --      Nothing after typechecking
654         (GRHSs id)
655
656 matchGroupArity :: MatchGroup id -> Arity
657 matchGroupArity (MatchGroup [] _) 
658   = panic "matchGroupArity"     -- MatchGroup is never empty
659 matchGroupArity (MatchGroup (match:matches) _)
660   = ASSERT( all ((== n_pats) . length . hsLMatchPats) matches )
661         -- Assertion just checks that all the matches have the same number of pats
662     n_pats
663   where
664     n_pats = length (hsLMatchPats match)
665
666 hsLMatchPats :: LMatch id -> [LPat id]
667 hsLMatchPats (L _ (Match pats _ _)) = pats
668
669 -- GRHSs are used both for pattern bindings and for Matches
670 data GRHSs id   
671   = GRHSs [LGRHS id]            -- Guarded RHSs
672           (HsLocalBinds id)     -- The where clause
673
674 type LGRHS id = Located (GRHS id)
675
676 data GRHS id = GRHS [LStmt id]          -- Guards
677                     (LHsExpr id)        -- Right hand side
678 \end{code}
679
680 We know the list must have at least one @Match@ in it.
681
682 \begin{code}
683 pprMatches :: (OutputableBndr idL, OutputableBndr idR) => HsMatchContext idL -> MatchGroup idR -> SDoc
684 pprMatches ctxt (MatchGroup matches ty) = vcat (map (pprMatch ctxt) (map unLoc matches))
685                                           -- Don't print the type; it's only 
686                                           -- a place-holder before typechecking
687
688 -- Exported to HsBinds, which can't see the defn of HsMatchContext
689 pprFunBind :: (OutputableBndr idL, OutputableBndr idR) => idL -> Bool -> MatchGroup idR -> SDoc
690 pprFunBind fun inf matches = pprMatches (FunRhs fun inf) matches
691
692 -- Exported to HsBinds, which can't see the defn of HsMatchContext
693 pprPatBind :: (OutputableBndr bndr, OutputableBndr id)
694            => LPat bndr -> GRHSs id -> SDoc
695 pprPatBind pat (grhss :: GRHSs id) = sep [ppr pat, nest 4 (pprGRHSs (PatBindRhs :: HsMatchContext id) grhss)]
696
697
698 pprMatch :: (OutputableBndr idL, OutputableBndr idR) => HsMatchContext idL -> Match idR -> SDoc
699 pprMatch ctxt (Match pats maybe_ty grhss)
700   = herald <+> sep [sep (map ppr other_pats), 
701                     ppr_maybe_ty, 
702                     nest 2 (pprGRHSs ctxt grhss)]
703   where
704     (herald, other_pats) 
705         = case ctxt of
706             FunRhs fun is_infix
707                 | not is_infix -> (ppr fun, pats)
708                         -- f x y z = e
709                         -- Not pprBndr; the AbsBinds will
710                         -- have printed the signature
711
712                 | null pats3 -> (pp_infix, [])
713                         -- x &&& y = e
714
715                 | otherwise -> (parens pp_infix, pats3)
716                         -- (x &&& y) z = e
717                 where
718                   (pat1:pat2:pats3) = pats
719                   pp_infix = ppr pat1 <+> ppr fun <+> ppr pat2
720
721             LambdaExpr -> (char '\\', pats)
722             other      -> (empty,     pats)
723
724     ppr_maybe_ty = case maybe_ty of
725                         Just ty -> dcolon <+> ppr ty
726                         Nothing -> empty
727
728
729 pprGRHSs :: (OutputableBndr idL, OutputableBndr idR) => HsMatchContext idL -> GRHSs idR -> SDoc
730 pprGRHSs ctxt (GRHSs grhss binds)
731   = vcat (map (pprGRHS ctxt . unLoc) grhss)
732  $$ if isEmptyLocalBinds binds then empty
733                                else text "where" $$ nest 4 (pprBinds binds)
734
735 pprGRHS :: (OutputableBndr idL, OutputableBndr idR) => HsMatchContext idL -> GRHS idR -> SDoc
736
737 pprGRHS ctxt (GRHS [] expr)
738  =  pp_rhs ctxt expr
739
740 pprGRHS ctxt (GRHS guards expr)
741  = sep [char '|' <+> interpp'SP guards, pp_rhs ctxt expr]
742
743 pp_rhs ctxt rhs = matchSeparator ctxt <+> pprDeeper (ppr rhs)
744 \end{code}
745
746 %************************************************************************
747 %*                                                                      *
748 \subsection{Do stmts and list comprehensions}
749 %*                                                                      *
750 %************************************************************************
751
752 \begin{code}
753 type LStmt id = Located (StmtLR id id)
754 type LStmtLR idL idR = Located (StmtLR idL idR)
755
756 type Stmt id = StmtLR id id
757
758 -- The SyntaxExprs in here are used *only* for do-notation, which
759 -- has rebindable syntax.  Otherwise they are unused.
760 data StmtLR idL idR
761   = BindStmt    (LPat idL)              
762                 (LHsExpr idR) 
763                 (SyntaxExpr idR)                -- The (>>=) operator
764                 (SyntaxExpr idR)                -- The fail operator 
765                 -- The fail operator is noSyntaxExpr 
766                 -- if the pattern match can't fail
767
768   | ExprStmt    (LHsExpr idR)
769                 (SyntaxExpr idR)                -- The (>>) operator
770                 PostTcType              -- Element type of the RHS (used for arrows)
771
772   | LetStmt     (HsLocalBindsLR idL idR)        
773
774         -- ParStmts only occur in a list comprehension
775   | ParStmt     [([LStmt idL], [idR])] -- After renaming, the ids are the binders
776                                          -- bound by the stmts and used subsequently
777
778         -- Recursive statement (see Note [RecStmt] below)
779   | RecStmt  [LStmtLR idL idR] 
780                 --- The next two fields are only valid after renaming
781              [idR]      -- The ids are a subset of the variables bound by the stmts
782                         -- that are used in stmts that follow the RecStmt
783
784              [idR]      -- Ditto, but these variables are the "recursive" ones, that 
785                         -- are used before they are bound in the stmts of the RecStmt
786                         -- From a type-checking point of view, these ones have to be monomorphic
787
788                 --- These fields are only valid after typechecking
789              [PostTcExpr]       -- These expressions correspond
790                                 -- 1-to-1 with the "recursive" [id], and are the expresions that 
791                                 -- should be returned by the recursion.  They may not quite be the
792                                 -- Ids themselves, because the Id may be *polymorphic*, but
793                                 -- the returned thing has to be *monomorphic*.
794              (DictBinds idR)    -- Method bindings of Ids bound by the RecStmt,
795                                 -- and used afterwards
796 \end{code}
797
798 ExprStmts are a bit tricky, because what they mean
799 depends on the context.  Consider the following contexts:
800
801         A do expression of type (m res_ty)
802         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
803         * ExprStmt E any_ty:   do { ....; E; ... }
804                 E :: m any_ty
805           Translation: E >> ...
806         
807         A list comprehensions of type [elt_ty]
808         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
809         * ExprStmt E Bool:   [ .. | .... E ]
810                         [ .. | ..., E, ... ]
811                         [ .. | .... | ..., E | ... ]
812                 E :: Bool
813           Translation: if E then fail else ...
814
815         A guard list, guarding a RHS of type rhs_ty
816         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
817         * ExprStmt E Bool:   f x | ..., E, ... = ...rhs...
818                 E :: Bool
819           Translation: if E then fail else ...
820         
821 Array comprehensions are handled like list comprehensions -=chak
822
823 Note [RecStmt]
824 ~~~~~~~~~~~~~~
825 Example:
826         HsDo [ BindStmt x ex
827
828              , RecStmt [a::forall a. a -> a, b] 
829                        [a::Int -> Int,       c] 
830                        [ BindStmt b (return x)
831                        , LetStmt a = ea
832                        , BindStmt c ec ]
833
834              , return (a b) ]
835
836 Here, the RecStmt binds a,b,c; but 
837   - Only a,b are used in the stmts *following* the RecStmt, 
838         This 'a' is *polymorphic'
839   - Only a,c are used in the stmts *inside* the RecStmt
840         *before* their bindings
841         This 'a' is monomorphic
842
843 Nota Bene: the two a's have different types, even though they
844 have the same Name.
845
846
847 \begin{code}
848 instance (OutputableBndr idL, OutputableBndr idR) => Outputable (StmtLR idL idR) where
849     ppr stmt = pprStmt stmt
850
851 pprStmt :: (OutputableBndr idL, OutputableBndr idR) => (StmtLR idL idR) -> SDoc
852 pprStmt (BindStmt pat expr _ _)   = hsep [ppr pat, ptext SLIT("<-"), ppr expr]
853 pprStmt (LetStmt binds)           = hsep [ptext SLIT("let"), pprBinds binds]
854 pprStmt (ExprStmt expr _ _)       = ppr expr
855 pprStmt (ParStmt stmtss)          = hsep (map (\stmts -> ptext SLIT("| ") <> ppr stmts) stmtss)
856 pprStmt (RecStmt segment _ _ _ _) = ptext SLIT("rec") <+> braces (vcat (map ppr segment))
857
858 pprDo :: OutputableBndr id => HsStmtContext any -> [LStmt id] -> LHsExpr id -> SDoc
859 pprDo DoExpr      stmts body = ptext SLIT("do")  <+> pprDeeperList vcat (map ppr stmts ++ [ppr body])
860 pprDo (MDoExpr _) stmts body = ptext SLIT("mdo") <+> pprDeeperList vcat (map ppr stmts ++ [ppr body])
861 pprDo ListComp    stmts body = pprComp brackets    stmts body
862 pprDo PArrComp    stmts body = pprComp pa_brackets stmts body
863 pprDo other       stmts body = panic "pprDo"    -- PatGuard, ParStmtCxt
864
865 pprComp :: OutputableBndr id => (SDoc -> SDoc) -> [LStmt id] -> LHsExpr id -> SDoc
866 pprComp brack quals body
867   = brack $
868         hang (ppr body <+> char '|')
869              4 (interpp'SP quals)
870 \end{code}
871
872 %************************************************************************
873 %*                                                                      *
874                 Template Haskell quotation brackets
875 %*                                                                      *
876 %************************************************************************
877
878 \begin{code}
879 data HsSplice id  = HsSplice    --  $z  or $(f 4)
880                         id              -- The id is just a unique name to 
881                         (LHsExpr id)    -- identify this splice point
882                                         
883 instance OutputableBndr id => Outputable (HsSplice id) where
884   ppr = pprSplice
885
886 pprSplice :: OutputableBndr id => HsSplice id -> SDoc
887 pprSplice (HsSplice n e) = char '$' <> ifPprDebug (brackets (ppr n)) <> pprParendExpr e
888
889
890 data HsBracket id = ExpBr (LHsExpr id)          -- [|  expr  |]
891                   | PatBr (LPat id)             -- [p| pat   |]
892                   | DecBr (HsGroup id)          -- [d| decls |]
893                   | TypBr (LHsType id)          -- [t| type  |]
894                   | VarBr id                    -- 'x, ''T
895
896 instance OutputableBndr id => Outputable (HsBracket id) where
897   ppr = pprHsBracket
898
899
900 pprHsBracket (ExpBr e) = thBrackets empty (ppr e)
901 pprHsBracket (PatBr p) = thBrackets (char 'p') (ppr p)
902 pprHsBracket (DecBr d) = thBrackets (char 'd') (ppr d)
903 pprHsBracket (TypBr t) = thBrackets (char 't') (ppr t)
904 pprHsBracket (VarBr n) = char '\'' <> ppr n
905         -- Infelicity: can't show ' vs '', because
906         -- we can't ask n what its OccName is, because the 
907         -- pretty-printer for HsExpr doesn't ask for NamedThings
908         -- But the pretty-printer for names will show the OccName class
909
910 thBrackets pp_kind pp_body = char '[' <> pp_kind <> char '|' <+> 
911                              pp_body <+> ptext SLIT("|]")
912 \end{code}
913
914 %************************************************************************
915 %*                                                                      *
916 \subsection{Enumerations and list comprehensions}
917 %*                                                                      *
918 %************************************************************************
919
920 \begin{code}
921 data ArithSeqInfo id
922   = From            (LHsExpr id)
923   | FromThen        (LHsExpr id)
924                     (LHsExpr id)
925   | FromTo          (LHsExpr id)
926                     (LHsExpr id)
927   | FromThenTo      (LHsExpr id)
928                     (LHsExpr id)
929                     (LHsExpr id)
930 \end{code}
931
932 \begin{code}
933 instance OutputableBndr id => Outputable (ArithSeqInfo id) where
934     ppr (From e1)               = hcat [ppr e1, pp_dotdot]
935     ppr (FromThen e1 e2)        = hcat [ppr e1, comma, space, ppr e2, pp_dotdot]
936     ppr (FromTo e1 e3)  = hcat [ppr e1, pp_dotdot, ppr e3]
937     ppr (FromThenTo e1 e2 e3)
938       = hcat [ppr e1, comma, space, ppr e2, pp_dotdot, ppr e3]
939
940 pp_dotdot = ptext SLIT(" .. ")
941 \end{code}
942
943
944 %************************************************************************
945 %*                                                                      *
946 \subsection{HsMatchCtxt}
947 %*                                                                      *
948 %************************************************************************
949
950 \begin{code}
951 data HsMatchContext id  -- Context of a Match
952   = FunRhs id Bool              -- Function binding for f; True <=> written infix
953   | CaseAlt                     -- Guard on a case alternative
954   | LambdaExpr                  -- Pattern of a lambda
955   | ProcExpr                    -- Pattern of a proc
956   | PatBindRhs                  -- Pattern binding
957   | RecUpd                      -- Record update [used only in DsExpr to tell matchWrapper
958                                 --      what sort of runtime error message to generate]
959   | StmtCtxt (HsStmtContext id) -- Pattern of a do-stmt or list comprehension
960   deriving ()
961
962 data HsStmtContext id
963   = ListComp 
964   | DoExpr 
965   | MDoExpr PostTcTable                 -- Recursive do-expression
966                                         -- (tiresomely, it needs table
967                                         --  of its return/bind ops)
968   | PArrComp                            -- Parallel array comprehension
969   | PatGuard (HsMatchContext id)        -- Pattern guard for specified thing
970   | ParStmtCtxt (HsStmtContext id)      -- A branch of a parallel stmt 
971 \end{code}
972
973 \begin{code}
974 isDoExpr :: HsStmtContext id -> Bool
975 isDoExpr DoExpr      = True
976 isDoExpr (MDoExpr _) = True
977 isDoExpr _           = False
978
979 isListCompExpr :: HsStmtContext id -> Bool
980 isListCompExpr ListComp = True
981 isListCompExpr PArrComp = True
982 isListCompExpr _        = False
983 \end{code}
984
985 \begin{code}
986 matchSeparator (FunRhs {})  = ptext SLIT("=")
987 matchSeparator CaseAlt      = ptext SLIT("->") 
988 matchSeparator LambdaExpr   = ptext SLIT("->") 
989 matchSeparator ProcExpr     = ptext SLIT("->") 
990 matchSeparator PatBindRhs   = ptext SLIT("=") 
991 matchSeparator (StmtCtxt _) = ptext SLIT("<-")  
992 matchSeparator RecUpd       = panic "unused"
993 \end{code}
994
995 \begin{code}
996 pprMatchContext (FunRhs fun _)    = ptext SLIT("the definition of") <+> quotes (ppr fun)
997 pprMatchContext CaseAlt           = ptext SLIT("a case alternative")
998 pprMatchContext RecUpd            = ptext SLIT("a record-update construct")
999 pprMatchContext PatBindRhs        = ptext SLIT("a pattern binding")
1000 pprMatchContext LambdaExpr        = ptext SLIT("a lambda abstraction")
1001 pprMatchContext ProcExpr          = ptext SLIT("an arrow abstraction")
1002 pprMatchContext (StmtCtxt ctxt)   = ptext SLIT("a pattern binding in") $$ pprStmtContext ctxt
1003
1004 pprStmtContext (ParStmtCtxt c) = sep [ptext SLIT("a parallel branch of"), pprStmtContext c]
1005 pprStmtContext (PatGuard ctxt) = ptext SLIT("a pattern guard for") $$ pprMatchContext ctxt
1006 pprStmtContext DoExpr          = ptext SLIT("a 'do' expression")
1007 pprStmtContext (MDoExpr _)     = ptext SLIT("an 'mdo' expression")
1008 pprStmtContext ListComp        = ptext SLIT("a list comprehension")
1009 pprStmtContext PArrComp        = ptext SLIT("an array comprehension")
1010
1011 {- 
1012 pprMatchRhsContext (FunRhs fun) = ptext SLIT("a right-hand side of function") <+> quotes (ppr fun)
1013 pprMatchRhsContext CaseAlt      = ptext SLIT("the body of a case alternative")
1014 pprMatchRhsContext PatBindRhs   = ptext SLIT("the right-hand side of a pattern binding")
1015 pprMatchRhsContext LambdaExpr   = ptext SLIT("the body of a lambda")
1016 pprMatchRhsContext ProcExpr     = ptext SLIT("the body of a proc")
1017 pprMatchRhsContext other        = panic "pprMatchRhsContext"    -- RecUpd, StmtCtxt
1018
1019 -- Used for the result statement of comprehension
1020 -- e.g. the 'e' in      [ e | ... ]
1021 --      or the 'r' in   f x = r
1022 pprStmtResultContext (PatGuard ctxt) = pprMatchRhsContext ctxt
1023 pprStmtResultContext other           = ptext SLIT("the result of") <+> pprStmtContext other
1024 -}
1025
1026 -- Used to generate the string for a *runtime* error message
1027 matchContextErrString (FunRhs fun _)             = "function " ++ showSDoc (ppr fun)
1028 matchContextErrString CaseAlt                    = "case"
1029 matchContextErrString PatBindRhs                 = "pattern binding"
1030 matchContextErrString RecUpd                     = "record update"
1031 matchContextErrString LambdaExpr                 = "lambda"
1032 matchContextErrString ProcExpr                   = "proc"
1033 matchContextErrString (StmtCtxt (ParStmtCtxt c)) = matchContextErrString (StmtCtxt c)
1034 matchContextErrString (StmtCtxt (PatGuard _))    = "pattern guard"
1035 matchContextErrString (StmtCtxt DoExpr)          = "'do' expression"
1036 matchContextErrString (StmtCtxt (MDoExpr _))     = "'mdo' expression"
1037 matchContextErrString (StmtCtxt ListComp)        = "list comprehension"
1038 matchContextErrString (StmtCtxt PArrComp)        = "array comprehension"
1039 \end{code}