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