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