2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
6 HsExpr: Abstract Haskell syntax: expressions
10 -- The above warning supression flag is a temporary kludge.
11 -- While working on this module you are encouraged to remove it and fix
12 -- any warnings in the module. See
13 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
18 #include "HsVersions.h"
39 %************************************************************************
41 \subsection{Expressions proper}
43 %************************************************************************
46 type LHsExpr id = Located (HsExpr id)
48 -------------------------
49 -- PostTcExpr is an evidence expression attached to the
50 -- syntax tree by the type checker (c.f. postTcType)
51 -- We use a PostTcTable where there are a bunch of pieces of
52 -- evidence, more than is convenient to keep individually
53 type PostTcExpr = HsExpr Id
54 type PostTcTable = [(Name, Id)]
56 noPostTcExpr :: PostTcExpr
57 noPostTcExpr = HsLit (HsString FSLIT("noPostTcExpr"))
59 noPostTcTable :: PostTcTable
62 -------------------------
63 -- SyntaxExpr is like PostTcExpr, but it's filled in a little earlier,
64 -- by the renamer. It's used for rebindable syntax.
65 -- E.g. (>>=) is filled in before the renamer by the appropriate Name
66 -- for (>>=), and then instantiated by the type checker with its
69 type SyntaxExpr id = HsExpr id
71 noSyntaxExpr :: SyntaxExpr id -- Before renaming, and sometimes after,
72 -- (if the syntax slot makes no sense)
73 noSyntaxExpr = HsLit (HsString FSLIT("noSyntaxExpr"))
76 type SyntaxTable id = [(Name, SyntaxExpr id)]
77 -- *** Currently used only for CmdTop (sigh) ***
78 -- * Before the renamer, this list is noSyntaxTable
80 -- * After the renamer, it takes the form [(std_name, HsVar actual_name)]
81 -- For example, for the 'return' op of a monad
82 -- normal case: (GHC.Base.return, HsVar GHC.Base.return)
83 -- with rebindable syntax: (GHC.Base.return, return_22)
84 -- where return_22 is whatever "return" is in scope
86 -- * After the type checker, it takes the form [(std_name, <expression>)]
87 -- where <expression> is the evidence for the method
89 noSyntaxTable :: SyntaxTable id
93 -------------------------
95 = HsVar id -- variable
96 | HsIPVar (IPName id) -- implicit parameter
97 | HsOverLit (HsOverLit id) -- Overloaded literals
99 | HsLit HsLit -- Simple (non-overloaded) literals
101 | HsLam (MatchGroup id) -- Currently always a single match
103 | HsApp (LHsExpr id) -- Application
106 -- Operator applications:
107 -- NB Bracketed ops such as (+) come out as Vars.
109 -- NB We need an expr for the operator in an OpApp/Section since
110 -- the typechecker may need to apply the operator to a few types.
112 | OpApp (LHsExpr id) -- left operand
113 (LHsExpr id) -- operator
114 Fixity -- Renamer adds fixity; bottom until then
115 (LHsExpr id) -- right operand
117 | NegApp (LHsExpr id) -- negated expr
118 (SyntaxExpr id) -- Name of 'negate'
120 | HsPar (LHsExpr id) -- parenthesised expr
122 | SectionL (LHsExpr id) -- operand
123 (LHsExpr id) -- operator
124 | SectionR (LHsExpr id) -- operator
125 (LHsExpr id) -- operand
127 | HsCase (LHsExpr id)
130 | HsIf (LHsExpr id) -- predicate
131 (LHsExpr id) -- then part
132 (LHsExpr id) -- else part
134 | HsLet (HsLocalBinds id) -- let(rec)
137 | HsDo (HsStmtContext Name) -- The parameterisation is unimportant
138 -- because in this context we never use
139 -- the PatGuard or ParStmt variant
140 [LStmt id] -- "do":one or more stmts
141 (LHsExpr id) -- The body; the last expression in the 'do'
142 -- of [ body | ... ] in a list comp
143 PostTcType -- Type of the whole expression
145 | ExplicitList -- syntactic list
146 PostTcType -- Gives type of components of list
149 | ExplicitPArr -- syntactic parallel array: [:e1, ..., en:]
150 PostTcType -- type of elements of the parallel array
153 | ExplicitTuple -- tuple
155 -- NB: Unit is ExplicitTuple []
156 -- for tuples, we can get the types
157 -- direct from the components
161 -- Record construction
162 | RecordCon (Located id) -- The constructor. After type checking
163 -- it's the dataConWrapId of the constructor
164 PostTcExpr -- Data con Id applied to type args
168 | RecordUpd (LHsExpr id)
170 [DataCon] -- Filled in by the type checker to the *non-empty*
171 -- list of DataCons that have all the upd'd fields
172 [PostTcType] -- Argument types of *input* record type
173 [PostTcType] -- and *output* record type
174 -- For a type family, the arg types are of the *instance* tycon, not the family tycon
176 | ExprWithTySig -- e :: type
180 | ExprWithTySigOut -- TRANSLATION
182 (LHsType Name) -- Retain the signature for round-tripping purposes
184 | ArithSeq -- arithmetic sequence
188 | PArrSeq -- arith. sequence for parallel array
189 PostTcExpr -- [:e1..e2:] or [:e1, e2..e3:]
192 | HsSCC FastString -- "set cost centre" (_scc_) annotation
193 (LHsExpr id) -- expr whose cost is to be measured
195 | HsCoreAnn FastString -- hdaume: core annotation
198 -----------------------------------------------------------
199 -- MetaHaskell Extensions
201 | HsBracket (HsBracket id)
203 | HsBracketOut (HsBracket Name) -- Output of the type checker is the *original*
204 [PendingSplice] -- renamed expression, plus *typechecked* splices
205 -- to be pasted back in by the desugarer
207 | HsSpliceE (HsSplice id)
209 -----------------------------------------------------------
210 -- Arrow notation extension
212 | HsProc (LPat id) -- arrow abstraction, proc
213 (LHsCmdTop id) -- body of the abstraction
214 -- always has an empty stack
216 ---------------------------------------
217 -- The following are commands, not expressions proper
219 | HsArrApp -- Arrow tail, or arrow application (f -< arg)
220 (LHsExpr id) -- arrow expression, f
221 (LHsExpr id) -- input expression, arg
222 PostTcType -- type of the arrow expressions f,
223 -- of the form a t t', where arg :: t
224 HsArrAppType -- higher-order (-<<) or first-order (-<)
225 Bool -- True => right-to-left (f -< arg)
226 -- False => left-to-right (arg >- f)
228 | HsArrForm -- Command formation, (| e cmd1 .. cmdn |)
229 (LHsExpr id) -- the operator
230 -- after type-checking, a type abstraction to be
231 -- applied to the type of the local environment tuple
232 (Maybe Fixity) -- fixity (filled in by the renamer), for forms that
233 -- were converted from OpApp's by the renamer
234 [LHsCmdTop id] -- argument commands
237 ---------------------------------------
238 -- Haskell program coverage (Hpc) Support
241 Int -- module-local tick number
242 [id] -- variables in scope
243 (LHsExpr id) -- sub-expression
246 Int -- module-local tick number for True
247 Int -- module-local tick number for False
248 (LHsExpr id) -- sub-expression
250 | HsTickPragma -- A pragma introduced tick
251 (FastString,(Int,Int),(Int,Int)) -- external span for this tick
254 ---------------------------------------
255 -- These constructors only appear temporarily in the parser.
256 -- The renamer translates them into the Right Thing.
258 | EWildPat -- wildcard
260 | EAsPat (Located id) -- as pattern
263 | EViewPat (LHsExpr id) -- view pattern
266 | ELazyPat (LHsExpr id) -- ~ pattern
268 | HsType (LHsType id) -- Explicit type argument; e.g f {| Int |} x y
270 ---------------------------------------
271 -- Finally, HsWrap appears only in typechecker output
273 | HsWrap HsWrapper -- TRANSLATION
276 type PendingSplice = (Name, LHsExpr Id) -- Typechecked splices, waiting to be
277 -- pasted back in by the desugarer
280 A @Dictionary@, unless of length 0 or 1, becomes a tuple. A
281 @ClassDictLam dictvars methods expr@ is, therefore:
283 \ x -> case x of ( dictvars-and-methods-tuple ) -> expr
287 instance OutputableBndr id => Outputable (HsExpr id) where
288 ppr expr = pprExpr expr
292 -----------------------
293 -- pprExpr, pprLExpr, pprBinds call pprDeeper;
294 -- the underscore versions do not
295 pprLExpr :: OutputableBndr id => LHsExpr id -> SDoc
296 pprLExpr (L _ e) = pprExpr e
298 pprExpr :: OutputableBndr id => HsExpr id -> SDoc
299 pprExpr e | isAtomicHsExpr e || isQuietHsExpr e = ppr_expr e
300 | otherwise = pprDeeper (ppr_expr e)
302 isQuietHsExpr :: HsExpr id -> Bool
303 -- Parentheses do display something, but it gives little info and
304 -- if we go deeper when we go inside them then we get ugly things
306 isQuietHsExpr (HsPar _) = True
307 -- applications don't display anything themselves
308 isQuietHsExpr (HsApp _ _) = True
309 isQuietHsExpr (OpApp _ _ _ _) = True
310 isQuietHsExpr _ = False
312 pprBinds :: (OutputableBndr idL, OutputableBndr idR) => HsLocalBindsLR idL idR -> SDoc
313 pprBinds b = pprDeeper (ppr b)
315 -----------------------
316 ppr_lexpr :: OutputableBndr id => LHsExpr id -> SDoc
317 ppr_lexpr e = ppr_expr (unLoc e)
319 ppr_expr :: OutputableBndr id => HsExpr id -> SDoc
320 ppr_expr (HsVar v) = pprHsVar v
321 ppr_expr (HsIPVar v) = ppr v
322 ppr_expr (HsLit lit) = ppr lit
323 ppr_expr (HsOverLit lit) = ppr lit
324 ppr_expr (HsPar e) = parens (ppr_lexpr e)
326 ppr_expr (HsCoreAnn s e)
327 = vcat [ptext SLIT("HsCoreAnn") <+> ftext s, ppr_lexpr e]
329 ppr_expr (HsApp e1 e2)
330 = let (fun, args) = collect_args e1 [e2] in
331 hang (ppr_lexpr fun) 2 (sep (map pprParendExpr args))
333 collect_args (L _ (HsApp fun arg)) args = collect_args fun (arg:args)
334 collect_args fun args = (fun, args)
336 ppr_expr (OpApp e1 op fixity e2)
338 HsVar v -> pp_infixly v
341 pp_e1 = pprDebugParendExpr e1 -- In debug mode, add parens
342 pp_e2 = pprDebugParendExpr e2 -- to make precedence clear
345 = hang (ppr op) 2 (sep [pp_e1, pp_e2])
348 = sep [nest 2 pp_e1, pprInfix v, nest 2 pp_e2]
350 ppr_expr (NegApp e _) = char '-' <+> pprDebugParendExpr e
352 ppr_expr (SectionL expr op)
354 HsVar v -> pp_infixly v
357 pp_expr = pprDebugParendExpr expr
359 pp_prefixly = hang (hsep [text " \\ x_ ->", ppr op])
360 4 (hsep [pp_expr, ptext SLIT("x_ )")])
361 pp_infixly v = (sep [pp_expr, pprInfix v])
363 ppr_expr (SectionR op expr)
365 HsVar v -> pp_infixly v
368 pp_expr = pprDebugParendExpr expr
370 pp_prefixly = hang (hsep [text "( \\ x_ ->", ppr op, ptext SLIT("x_")])
371 4 ((<>) pp_expr rparen)
373 = (sep [pprInfix v, pp_expr])
375 ppr_expr (HsLam matches :: HsExpr id)
376 = pprMatches (LambdaExpr :: HsMatchContext id) matches
378 ppr_expr (HsCase expr matches :: HsExpr id)
379 = sep [ sep [ptext SLIT("case"), nest 4 (ppr expr), ptext SLIT("of")],
380 nest 2 (pprMatches (CaseAlt :: HsMatchContext id) matches) ]
382 ppr_expr (HsIf e1 e2 e3)
383 = sep [hsep [ptext SLIT("if"), nest 2 (ppr e1), ptext SLIT("then")],
388 -- special case: let ... in let ...
389 ppr_expr (HsLet binds expr@(L _ (HsLet _ _)))
390 = sep [hang (ptext SLIT("let")) 2 (hsep [pprBinds binds, ptext SLIT("in")]),
393 ppr_expr (HsLet binds expr)
394 = sep [hang (ptext SLIT("let")) 2 (pprBinds binds),
395 hang (ptext SLIT("in")) 2 (ppr expr)]
397 ppr_expr (HsDo do_or_list_comp stmts body _) = pprDo do_or_list_comp stmts body
399 ppr_expr (ExplicitList _ exprs)
400 = brackets (pprDeeperList fsep (punctuate comma (map ppr_lexpr exprs)))
402 ppr_expr (ExplicitPArr _ exprs)
403 = pa_brackets (pprDeeperList fsep (punctuate comma (map ppr_lexpr exprs)))
405 ppr_expr (ExplicitTuple exprs boxity)
406 = tupleParens boxity (sep (punctuate comma (map ppr_lexpr exprs)))
408 ppr_expr (RecordCon con_id con_expr rbinds)
409 = hang (ppr con_id) 2 (ppr rbinds)
411 ppr_expr (RecordUpd aexp rbinds _ _ _)
412 = hang (pprParendExpr aexp) 2 (ppr rbinds)
414 ppr_expr (ExprWithTySig expr sig)
415 = hang (nest 2 (ppr_lexpr expr) <+> dcolon)
417 ppr_expr (ExprWithTySigOut expr sig)
418 = hang (nest 2 (ppr_lexpr expr) <+> dcolon)
421 ppr_expr (ArithSeq expr info) = brackets (ppr info)
422 ppr_expr (PArrSeq expr info) = pa_brackets (ppr info)
424 ppr_expr EWildPat = char '_'
425 ppr_expr (ELazyPat e) = char '~' <> pprParendExpr e
426 ppr_expr (EAsPat v e) = ppr v <> char '@' <> pprParendExpr e
428 ppr_expr (HsSCC lbl expr)
429 = sep [ ptext SLIT("_scc_") <+> doubleQuotes (ftext lbl), pprParendExpr expr ]
431 ppr_expr (HsWrap co_fn e) = pprHsWrapper (pprExpr e) co_fn
432 ppr_expr (HsType id) = ppr id
434 ppr_expr (HsSpliceE s) = pprSplice s
435 ppr_expr (HsBracket b) = pprHsBracket b
436 ppr_expr (HsBracketOut e []) = ppr e
437 ppr_expr (HsBracketOut e ps) = ppr e $$ ptext SLIT("pending") <+> ppr ps
439 ppr_expr (HsProc pat (L _ (HsCmdTop cmd _ _ _)))
440 = hsep [ptext SLIT("proc"), ppr pat, ptext SLIT("->"), ppr cmd]
442 ppr_expr (HsTick tickId vars exp)
443 = hcat [ptext SLIT("tick<"), ppr tickId,ptext SLIT(">("), hsep (map pprHsVar vars), ppr exp,ptext SLIT(")")]
444 ppr_expr (HsBinTick tickIdTrue tickIdFalse exp)
445 = hcat [ptext SLIT("bintick<"),
450 ppr exp,ptext SLIT(")")]
451 ppr_expr (HsTickPragma externalSrcLoc exp)
452 = hcat [ptext SLIT("tickpragma<"), ppr externalSrcLoc,ptext SLIT(">("), ppr exp,ptext SLIT(")")]
454 ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp True)
455 = hsep [ppr_lexpr arrow, ptext SLIT("-<"), ppr_lexpr arg]
456 ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp False)
457 = hsep [ppr_lexpr arg, ptext SLIT(">-"), ppr_lexpr arrow]
458 ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp True)
459 = hsep [ppr_lexpr arrow, ptext SLIT("-<<"), ppr_lexpr arg]
460 ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp False)
461 = hsep [ppr_lexpr arg, ptext SLIT(">>-"), ppr_lexpr arrow]
463 ppr_expr (HsArrForm (L _ (HsVar v)) (Just _) [arg1, arg2])
464 = sep [pprCmdArg (unLoc arg1), hsep [pprInfix v, pprCmdArg (unLoc arg2)]]
465 ppr_expr (HsArrForm op _ args)
466 = hang (ptext SLIT("(|") <> ppr_lexpr op)
467 4 (sep (map (pprCmdArg.unLoc) args) <> ptext SLIT("|)"))
469 pprCmdArg :: OutputableBndr id => HsCmdTop id -> SDoc
470 pprCmdArg (HsCmdTop cmd@(L _ (HsArrForm _ Nothing [])) _ _ _)
472 pprCmdArg (HsCmdTop cmd _ _ _)
473 = parens (ppr_lexpr cmd)
475 -- Put a var in backquotes if it's not an operator already
476 pprInfix :: Outputable name => name -> SDoc
477 pprInfix v | isOperator ppr_v = ppr_v
478 | otherwise = char '`' <> ppr_v <> char '`'
482 -- add parallel array brackets around a document
484 pa_brackets :: SDoc -> SDoc
485 pa_brackets p = ptext SLIT("[:") <> p <> ptext SLIT(":]")
488 HsSyn records exactly where the user put parens, with HsPar.
489 So generally speaking we print without adding any parens.
490 However, some code is internally generated, and in some places
491 parens are absolutely required; so for these places we use
492 pprParendExpr (but don't print double parens of course).
494 For operator applications we don't add parens, because the oprerator
495 fixities should do the job, except in debug mode (-dppr-debug) so we
496 can see the structure of the parse tree.
499 pprDebugParendExpr :: OutputableBndr id => LHsExpr id -> SDoc
500 pprDebugParendExpr expr
501 = getPprStyle (\sty ->
502 if debugStyle sty then pprParendExpr expr
505 pprParendExpr :: OutputableBndr id => LHsExpr id -> SDoc
508 pp_as_was = pprLExpr expr
509 -- Using pprLExpr makes sure that we go 'deeper'
510 -- I think that is usually (always?) right
514 HsOverLit l -> pp_as_was
516 HsIPVar _ -> pp_as_was
517 ExplicitList _ _ -> pp_as_was
518 ExplicitPArr _ _ -> pp_as_was
519 ExplicitTuple _ _ -> pp_as_was
521 HsBracket _ -> pp_as_was
522 HsBracketOut _ [] -> pp_as_was
524 | isListCompExpr sc -> pp_as_was
525 _ -> parens pp_as_was
527 isAtomicHsExpr :: HsExpr id -> Bool -- A single token
528 isAtomicHsExpr (HsVar {}) = True
529 isAtomicHsExpr (HsLit {}) = True
530 isAtomicHsExpr (HsOverLit {}) = True
531 isAtomicHsExpr (HsIPVar {}) = True
532 isAtomicHsExpr (HsWrap _ e) = isAtomicHsExpr e
533 isAtomicHsExpr (HsPar e) = isAtomicHsExpr (unLoc e)
534 isAtomicHsExpr e = False
537 %************************************************************************
539 \subsection{Commands (in arrow abstractions)}
541 %************************************************************************
543 We re-use HsExpr to represent these.
546 type HsCmd id = HsExpr id
548 type LHsCmd id = LHsExpr id
550 data HsArrAppType = HsHigherOrderApp | HsFirstOrderApp
553 The legal constructors for commands are:
555 = HsArrApp ... -- as above
557 | HsArrForm ... -- as above
562 | HsLam (Match id) -- kappa
564 -- the renamer turns this one into HsArrForm
565 | OpApp (HsExpr id) -- left operand
566 (HsCmd id) -- operator
567 Fixity -- Renamer adds fixity; bottom until then
568 (HsCmd id) -- right operand
570 | HsPar (HsCmd id) -- parenthesised command
573 [Match id] -- bodies are HsCmd's
576 | HsIf (HsExpr id) -- predicate
577 (HsCmd id) -- then part
578 (HsCmd id) -- else part
581 | HsLet (HsLocalBinds id) -- let(rec)
584 | HsDo (HsStmtContext Name) -- The parameterisation is unimportant
585 -- because in this context we never use
586 -- the PatGuard or ParStmt variant
587 [Stmt id] -- HsExpr's are really HsCmd's
588 PostTcType -- Type of the whole expression
591 Top-level command, introducing a new arrow.
592 This may occur inside a proc (where the stack is empty) or as an
593 argument of a command-forming operator.
596 type LHsCmdTop id = Located (HsCmdTop id)
599 = HsCmdTop (LHsCmd id)
600 [PostTcType] -- types of inputs on the command's stack
601 PostTcType -- return type of the command
603 -- after type checking:
604 -- names used in the command's desugaring
607 %************************************************************************
609 \subsection{Record binds}
611 %************************************************************************
614 type HsRecordBinds id = HsRecFields id (LHsExpr id)
619 %************************************************************************
621 \subsection{@Match@, @GRHSs@, and @GRHS@ datatypes}
623 %************************************************************************
625 @Match@es are sets of pattern bindings and right hand sides for
626 functions, patterns or case branches. For example, if a function @g@
632 then \tr{g} has two @Match@es: @(x,y) = y@ and @((x:ys),y) = y+1@.
634 It is always the case that each element of an @[Match]@ list has the
635 same number of @pats@s inside it. This corresponds to saying that
636 a function defined by pattern matching must have the same number of
637 patterns in each equation.
642 [LMatch id] -- The alternatives
643 PostTcType -- The type is the type of the entire group
644 -- t1 -> ... -> tn -> tr
645 -- where there are n patterns
647 type LMatch id = Located (Match id)
651 [LPat id] -- The patterns
652 (Maybe (LHsType id)) -- A type signature for the result of the match
653 -- Nothing after typechecking
656 matchGroupArity :: MatchGroup id -> Arity
657 matchGroupArity (MatchGroup [] _)
658 = panic "matchGroupArity" -- MatchGroup is never empty
659 matchGroupArity (MatchGroup (match:matches) _)
660 = ASSERT( all ((== n_pats) . length . hsLMatchPats) matches )
661 -- Assertion just checks that all the matches have the same number of pats
664 n_pats = length (hsLMatchPats match)
666 hsLMatchPats :: LMatch id -> [LPat id]
667 hsLMatchPats (L _ (Match pats _ _)) = pats
669 -- GRHSs are used both for pattern bindings and for Matches
671 = GRHSs [LGRHS id] -- Guarded RHSs
672 (HsLocalBinds id) -- The where clause
674 type LGRHS id = Located (GRHS id)
676 data GRHS id = GRHS [LStmt id] -- Guards
677 (LHsExpr id) -- Right hand side
680 We know the list must have at least one @Match@ in it.
683 pprMatches :: (OutputableBndr idL, OutputableBndr idR) => HsMatchContext idL -> MatchGroup idR -> SDoc
684 pprMatches ctxt (MatchGroup matches ty) = vcat (map (pprMatch ctxt) (map unLoc matches))
685 -- Don't print the type; it's only
686 -- a place-holder before typechecking
688 -- Exported to HsBinds, which can't see the defn of HsMatchContext
689 pprFunBind :: (OutputableBndr idL, OutputableBndr idR) => idL -> Bool -> MatchGroup idR -> SDoc
690 pprFunBind fun inf matches = pprMatches (FunRhs fun inf) matches
692 -- Exported to HsBinds, which can't see the defn of HsMatchContext
693 pprPatBind :: (OutputableBndr bndr, OutputableBndr id)
694 => LPat bndr -> GRHSs id -> SDoc
695 pprPatBind pat (grhss :: GRHSs id) = sep [ppr pat, nest 4 (pprGRHSs (PatBindRhs :: HsMatchContext id) grhss)]
698 pprMatch :: (OutputableBndr idL, OutputableBndr idR) => HsMatchContext idL -> Match idR -> SDoc
699 pprMatch ctxt (Match pats maybe_ty grhss)
700 = herald <+> sep [sep (map ppr other_pats),
702 nest 2 (pprGRHSs ctxt grhss)]
707 | not is_infix -> (ppr fun, pats)
709 -- Not pprBndr; the AbsBinds will
710 -- have printed the signature
712 | null pats3 -> (pp_infix, [])
715 | otherwise -> (parens pp_infix, pats3)
718 (pat1:pat2:pats3) = pats
719 pp_infix = ppr pat1 <+> ppr fun <+> ppr pat2
721 LambdaExpr -> (char '\\', pats)
722 other -> (empty, pats)
724 ppr_maybe_ty = case maybe_ty of
725 Just ty -> dcolon <+> ppr ty
729 pprGRHSs :: (OutputableBndr idL, OutputableBndr idR) => HsMatchContext idL -> GRHSs idR -> SDoc
730 pprGRHSs ctxt (GRHSs grhss binds)
731 = vcat (map (pprGRHS ctxt . unLoc) grhss)
732 $$ if isEmptyLocalBinds binds then empty
733 else text "where" $$ nest 4 (pprBinds binds)
735 pprGRHS :: (OutputableBndr idL, OutputableBndr idR) => HsMatchContext idL -> GRHS idR -> SDoc
737 pprGRHS ctxt (GRHS [] expr)
740 pprGRHS ctxt (GRHS guards expr)
741 = sep [char '|' <+> interpp'SP guards, pp_rhs ctxt expr]
743 pp_rhs ctxt rhs = matchSeparator ctxt <+> pprDeeper (ppr rhs)
746 %************************************************************************
748 \subsection{Do stmts and list comprehensions}
750 %************************************************************************
753 type LStmt id = Located (StmtLR id id)
754 type LStmtLR idL idR = Located (StmtLR idL idR)
756 type Stmt id = StmtLR id id
758 -- The SyntaxExprs in here are used *only* for do-notation, which
759 -- has rebindable syntax. Otherwise they are unused.
761 = BindStmt (LPat idL)
763 (SyntaxExpr idR) -- The (>>=) operator
764 (SyntaxExpr idR) -- The fail operator
765 -- The fail operator is noSyntaxExpr
766 -- if the pattern match can't fail
768 | ExprStmt (LHsExpr idR)
769 (SyntaxExpr idR) -- The (>>) operator
770 PostTcType -- Element type of the RHS (used for arrows)
772 | LetStmt (HsLocalBindsLR idL idR)
774 -- ParStmts only occur in a list comprehension
775 | ParStmt [([LStmt idL], [idR])] -- After renaming, the ids are the binders
776 -- bound by the stmts and used subsequently
778 -- Recursive statement (see Note [RecStmt] below)
779 | RecStmt [LStmtLR idL idR]
780 --- The next two fields are only valid after renaming
781 [idR] -- The ids are a subset of the variables bound by the stmts
782 -- that are used in stmts that follow the RecStmt
784 [idR] -- Ditto, but these variables are the "recursive" ones, that
785 -- are used before they are bound in the stmts of the RecStmt
786 -- From a type-checking point of view, these ones have to be monomorphic
788 --- These fields are only valid after typechecking
789 [PostTcExpr] -- These expressions correspond
790 -- 1-to-1 with the "recursive" [id], and are the expresions that
791 -- should be returned by the recursion. They may not quite be the
792 -- Ids themselves, because the Id may be *polymorphic*, but
793 -- the returned thing has to be *monomorphic*.
794 (DictBinds idR) -- Method bindings of Ids bound by the RecStmt,
795 -- and used afterwards
798 ExprStmts are a bit tricky, because what they mean
799 depends on the context. Consider the following contexts:
801 A do expression of type (m res_ty)
802 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
803 * ExprStmt E any_ty: do { ....; E; ... }
805 Translation: E >> ...
807 A list comprehensions of type [elt_ty]
808 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
809 * ExprStmt E Bool: [ .. | .... E ]
811 [ .. | .... | ..., E | ... ]
813 Translation: if E then fail else ...
815 A guard list, guarding a RHS of type rhs_ty
816 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
817 * ExprStmt E Bool: f x | ..., E, ... = ...rhs...
819 Translation: if E then fail else ...
821 Array comprehensions are handled like list comprehensions -=chak
828 , RecStmt [a::forall a. a -> a, b]
830 [ BindStmt b (return x)
836 Here, the RecStmt binds a,b,c; but
837 - Only a,b are used in the stmts *following* the RecStmt,
838 This 'a' is *polymorphic'
839 - Only a,c are used in the stmts *inside* the RecStmt
840 *before* their bindings
841 This 'a' is monomorphic
843 Nota Bene: the two a's have different types, even though they
848 instance (OutputableBndr idL, OutputableBndr idR) => Outputable (StmtLR idL idR) where
849 ppr stmt = pprStmt stmt
851 pprStmt :: (OutputableBndr idL, OutputableBndr idR) => (StmtLR idL idR) -> SDoc
852 pprStmt (BindStmt pat expr _ _) = hsep [ppr pat, ptext SLIT("<-"), ppr expr]
853 pprStmt (LetStmt binds) = hsep [ptext SLIT("let"), pprBinds binds]
854 pprStmt (ExprStmt expr _ _) = ppr expr
855 pprStmt (ParStmt stmtss) = hsep (map (\stmts -> ptext SLIT("| ") <> ppr stmts) stmtss)
856 pprStmt (RecStmt segment _ _ _ _) = ptext SLIT("rec") <+> braces (vcat (map ppr segment))
858 pprDo :: OutputableBndr id => HsStmtContext any -> [LStmt id] -> LHsExpr id -> SDoc
859 pprDo DoExpr stmts body = ptext SLIT("do") <+> pprDeeperList vcat (map ppr stmts ++ [ppr body])
860 pprDo (MDoExpr _) stmts body = ptext SLIT("mdo") <+> pprDeeperList vcat (map ppr stmts ++ [ppr body])
861 pprDo ListComp stmts body = pprComp brackets stmts body
862 pprDo PArrComp stmts body = pprComp pa_brackets stmts body
863 pprDo other stmts body = panic "pprDo" -- PatGuard, ParStmtCxt
865 pprComp :: OutputableBndr id => (SDoc -> SDoc) -> [LStmt id] -> LHsExpr id -> SDoc
866 pprComp brack quals body
868 hang (ppr body <+> char '|')
872 %************************************************************************
874 Template Haskell quotation brackets
876 %************************************************************************
879 data HsSplice id = HsSplice -- $z or $(f 4)
880 id -- The id is just a unique name to
881 (LHsExpr id) -- identify this splice point
883 instance OutputableBndr id => Outputable (HsSplice id) where
886 pprSplice :: OutputableBndr id => HsSplice id -> SDoc
887 pprSplice (HsSplice n e) = char '$' <> ifPprDebug (brackets (ppr n)) <> pprParendExpr e
890 data HsBracket id = ExpBr (LHsExpr id) -- [| expr |]
891 | PatBr (LPat id) -- [p| pat |]
892 | DecBr (HsGroup id) -- [d| decls |]
893 | TypBr (LHsType id) -- [t| type |]
894 | VarBr id -- 'x, ''T
896 instance OutputableBndr id => Outputable (HsBracket id) where
900 pprHsBracket (ExpBr e) = thBrackets empty (ppr e)
901 pprHsBracket (PatBr p) = thBrackets (char 'p') (ppr p)
902 pprHsBracket (DecBr d) = thBrackets (char 'd') (ppr d)
903 pprHsBracket (TypBr t) = thBrackets (char 't') (ppr t)
904 pprHsBracket (VarBr n) = char '\'' <> ppr n
905 -- Infelicity: can't show ' vs '', because
906 -- we can't ask n what its OccName is, because the
907 -- pretty-printer for HsExpr doesn't ask for NamedThings
908 -- But the pretty-printer for names will show the OccName class
910 thBrackets pp_kind pp_body = char '[' <> pp_kind <> char '|' <+>
911 pp_body <+> ptext SLIT("|]")
914 %************************************************************************
916 \subsection{Enumerations and list comprehensions}
918 %************************************************************************
923 | FromThen (LHsExpr id)
925 | FromTo (LHsExpr id)
927 | FromThenTo (LHsExpr id)
933 instance OutputableBndr id => Outputable (ArithSeqInfo id) where
934 ppr (From e1) = hcat [ppr e1, pp_dotdot]
935 ppr (FromThen e1 e2) = hcat [ppr e1, comma, space, ppr e2, pp_dotdot]
936 ppr (FromTo e1 e3) = hcat [ppr e1, pp_dotdot, ppr e3]
937 ppr (FromThenTo e1 e2 e3)
938 = hcat [ppr e1, comma, space, ppr e2, pp_dotdot, ppr e3]
940 pp_dotdot = ptext SLIT(" .. ")
944 %************************************************************************
946 \subsection{HsMatchCtxt}
948 %************************************************************************
951 data HsMatchContext id -- Context of a Match
952 = FunRhs id Bool -- Function binding for f; True <=> written infix
953 | CaseAlt -- Guard on a case alternative
954 | LambdaExpr -- Pattern of a lambda
955 | ProcExpr -- Pattern of a proc
956 | PatBindRhs -- Pattern binding
957 | RecUpd -- Record update [used only in DsExpr to tell matchWrapper
958 -- what sort of runtime error message to generate]
959 | StmtCtxt (HsStmtContext id) -- Pattern of a do-stmt or list comprehension
962 data HsStmtContext id
965 | MDoExpr PostTcTable -- Recursive do-expression
966 -- (tiresomely, it needs table
967 -- of its return/bind ops)
968 | PArrComp -- Parallel array comprehension
969 | PatGuard (HsMatchContext id) -- Pattern guard for specified thing
970 | ParStmtCtxt (HsStmtContext id) -- A branch of a parallel stmt
974 isDoExpr :: HsStmtContext id -> Bool
975 isDoExpr DoExpr = True
976 isDoExpr (MDoExpr _) = True
979 isListCompExpr :: HsStmtContext id -> Bool
980 isListCompExpr ListComp = True
981 isListCompExpr PArrComp = True
982 isListCompExpr _ = False
986 matchSeparator (FunRhs {}) = ptext SLIT("=")
987 matchSeparator CaseAlt = ptext SLIT("->")
988 matchSeparator LambdaExpr = ptext SLIT("->")
989 matchSeparator ProcExpr = ptext SLIT("->")
990 matchSeparator PatBindRhs = ptext SLIT("=")
991 matchSeparator (StmtCtxt _) = ptext SLIT("<-")
992 matchSeparator RecUpd = panic "unused"
996 pprMatchContext (FunRhs fun _) = ptext SLIT("the definition of") <+> quotes (ppr fun)
997 pprMatchContext CaseAlt = ptext SLIT("a case alternative")
998 pprMatchContext RecUpd = ptext SLIT("a record-update construct")
999 pprMatchContext PatBindRhs = ptext SLIT("a pattern binding")
1000 pprMatchContext LambdaExpr = ptext SLIT("a lambda abstraction")
1001 pprMatchContext ProcExpr = ptext SLIT("an arrow abstraction")
1002 pprMatchContext (StmtCtxt ctxt) = ptext SLIT("a pattern binding in") $$ pprStmtContext ctxt
1004 pprStmtContext (ParStmtCtxt c) = sep [ptext SLIT("a parallel branch of"), pprStmtContext c]
1005 pprStmtContext (PatGuard ctxt) = ptext SLIT("a pattern guard for") $$ pprMatchContext ctxt
1006 pprStmtContext DoExpr = ptext SLIT("a 'do' expression")
1007 pprStmtContext (MDoExpr _) = ptext SLIT("an 'mdo' expression")
1008 pprStmtContext ListComp = ptext SLIT("a list comprehension")
1009 pprStmtContext PArrComp = ptext SLIT("an array comprehension")
1012 pprMatchRhsContext (FunRhs fun) = ptext SLIT("a right-hand side of function") <+> quotes (ppr fun)
1013 pprMatchRhsContext CaseAlt = ptext SLIT("the body of a case alternative")
1014 pprMatchRhsContext PatBindRhs = ptext SLIT("the right-hand side of a pattern binding")
1015 pprMatchRhsContext LambdaExpr = ptext SLIT("the body of a lambda")
1016 pprMatchRhsContext ProcExpr = ptext SLIT("the body of a proc")
1017 pprMatchRhsContext other = panic "pprMatchRhsContext" -- RecUpd, StmtCtxt
1019 -- Used for the result statement of comprehension
1020 -- e.g. the 'e' in [ e | ... ]
1021 -- or the 'r' in f x = r
1022 pprStmtResultContext (PatGuard ctxt) = pprMatchRhsContext ctxt
1023 pprStmtResultContext other = ptext SLIT("the result of") <+> pprStmtContext other
1026 -- Used to generate the string for a *runtime* error message
1027 matchContextErrString (FunRhs fun _) = "function " ++ showSDoc (ppr fun)
1028 matchContextErrString CaseAlt = "case"
1029 matchContextErrString PatBindRhs = "pattern binding"
1030 matchContextErrString RecUpd = "record update"
1031 matchContextErrString LambdaExpr = "lambda"
1032 matchContextErrString ProcExpr = "proc"
1033 matchContextErrString (StmtCtxt (ParStmtCtxt c)) = matchContextErrString (StmtCtxt c)
1034 matchContextErrString (StmtCtxt (PatGuard _)) = "pattern guard"
1035 matchContextErrString (StmtCtxt DoExpr) = "'do' expression"
1036 matchContextErrString (StmtCtxt (MDoExpr _)) = "'mdo' expression"
1037 matchContextErrString (StmtCtxt ListComp) = "list comprehension"
1038 matchContextErrString (StmtCtxt PArrComp) = "array comprehension"