2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
7 -- | Abstract Haskell syntax for expressions.
10 #include "HsVersions.h"
30 %************************************************************************
32 \subsection{Expressions proper}
34 %************************************************************************
37 -- * Expressions proper
39 type LHsExpr id = Located (HsExpr id)
41 -------------------------
42 -- | PostTcExpr is an evidence expression attached to the syntax tree by the
43 -- type checker (c.f. postTcType).
44 type PostTcExpr = HsExpr Id
45 -- | We use a PostTcTable where there are a bunch of pieces of evidence, more
46 -- than is convenient to keep individually.
47 type PostTcTable = [(Name, Id)]
49 noPostTcExpr :: PostTcExpr
50 noPostTcExpr = HsLit (HsString (fsLit "noPostTcExpr"))
52 noPostTcTable :: PostTcTable
55 -------------------------
56 -- | SyntaxExpr is like 'PostTcExpr', but it's filled in a little earlier,
57 -- by the renamer. It's used for rebindable syntax.
59 -- E.g. @(>>=)@ is filled in before the renamer by the appropriate 'Name' for
60 -- @(>>=)@, and then instantiated by the type checker with its type args
63 type SyntaxExpr id = HsExpr id
65 noSyntaxExpr :: SyntaxExpr id -- Before renaming, and sometimes after,
66 -- (if the syntax slot makes no sense)
67 noSyntaxExpr = HsLit (HsString (fsLit "noSyntaxExpr"))
70 type SyntaxTable id = [(Name, SyntaxExpr id)]
71 -- ^ Currently used only for 'CmdTop' (sigh)
73 -- * Before the renamer, this list is 'noSyntaxTable'
75 -- * After the renamer, it takes the form @[(std_name, HsVar actual_name)]@
76 -- For example, for the 'return' op of a monad
78 -- * normal case: @(GHC.Base.return, HsVar GHC.Base.return)@
80 -- * with rebindable syntax: @(GHC.Base.return, return_22)@
81 -- where @return_22@ is whatever @return@ is in scope
83 -- * After the type checker, it takes the form @[(std_name, <expression>)]@
84 -- where @<expression>@ is the evidence for the method
86 noSyntaxTable :: SyntaxTable id
90 -------------------------
91 -- | A Haskell expression.
93 = HsVar id -- ^ variable
94 | HsIPVar (IPName id) -- ^ implicit parameter
95 | HsOverLit (HsOverLit id) -- ^ Overloaded literals
97 | HsLit HsLit -- ^ Simple (non-overloaded) literals
99 | HsLam (MatchGroup id) -- Currently always a single match
101 | HsApp (LHsExpr id) (LHsExpr id) -- Application
103 -- Operator applications:
104 -- NB Bracketed ops such as (+) come out as Vars.
106 -- NB We need an expr for the operator in an OpApp/Section since
107 -- the typechecker may need to apply the operator to a few types.
109 | OpApp (LHsExpr id) -- left operand
110 (LHsExpr id) -- operator
111 Fixity -- Renamer adds fixity; bottom until then
112 (LHsExpr id) -- right operand
114 | NegApp (LHsExpr id) -- negated expr
115 (SyntaxExpr id) -- Name of 'negate'
117 | HsPar (LHsExpr id) -- parenthesised expr
119 | SectionL (LHsExpr id) -- operand
120 (LHsExpr id) -- operator
121 | SectionR (LHsExpr id) -- operator
122 (LHsExpr id) -- operand
124 | HsCase (LHsExpr id)
127 | HsIf (LHsExpr id) -- predicate
128 (LHsExpr id) -- then part
129 (LHsExpr id) -- else part
131 | HsLet (HsLocalBinds id) -- let(rec)
134 | HsDo (HsStmtContext Name) -- The parameterisation is unimportant
135 -- because in this context we never use
136 -- the PatGuard or ParStmt variant
137 [LStmt id] -- "do":one or more stmts
138 (LHsExpr id) -- The body; the last expression in the
139 -- 'do' of [ body | ... ] in a list comp
140 PostTcType -- Type of the whole expression
142 | ExplicitList -- syntactic list
143 PostTcType -- Gives type of components of list
146 | ExplicitPArr -- syntactic parallel array: [:e1, ..., en:]
147 PostTcType -- type of elements of the parallel array
150 | ExplicitTuple -- tuple
152 -- NB: Unit is ExplicitTuple []
153 -- for tuples, we can get the types
154 -- direct from the components
158 -- Record construction
159 | RecordCon (Located id) -- The constructor. After type checking
160 -- it's the dataConWrapId of the constructor
161 PostTcExpr -- Data con Id applied to type args
165 | RecordUpd (LHsExpr id)
167 -- (HsMatchGroup Id) -- Filled in by the type checker to be
168 -- -- a match that does the job
169 [DataCon] -- Filled in by the type checker to the
170 -- _non-empty_ list of DataCons that have
171 -- 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,
175 -- not the family tycon
177 | ExprWithTySig -- e :: type
181 | ExprWithTySigOut -- TRANSLATION
183 (LHsType Name) -- Retain the signature for
184 -- round-tripping purposes
186 | ArithSeq -- arithmetic sequence
190 | PArrSeq -- arith. sequence for parallel array
191 PostTcExpr -- [:e1..e2:] or [:e1, e2..e3:]
194 | HsSCC FastString -- "set cost centre" SCC pragma
195 (LHsExpr id) -- expr whose cost is to be measured
197 | HsCoreAnn FastString -- hdaume: core annotation
200 -----------------------------------------------------------
201 -- MetaHaskell Extensions
203 | HsBracket (HsBracket id)
205 | HsBracketOut (HsBracket Name) -- Output of the type checker is
207 [PendingSplice] -- renamed expression, plus
208 -- _typechecked_ splices to be
209 -- pasted back in by the desugarer
211 | HsSpliceE (HsSplice id)
213 | HsQuasiQuoteE (HsQuasiQuote id)
214 -- See Note [Quasi-quote overview] in TcSplice
216 -----------------------------------------------------------
217 -- Arrow notation extension
219 | HsProc (LPat id) -- arrow abstraction, proc
220 (LHsCmdTop id) -- body of the abstraction
221 -- always has an empty stack
223 ---------------------------------------
224 -- The following are commands, not expressions proper
226 | HsArrApp -- Arrow tail, or arrow application (f -< arg)
227 (LHsExpr id) -- arrow expression, f
228 (LHsExpr id) -- input expression, arg
229 PostTcType -- type of the arrow expressions f,
230 -- of the form a t t', where arg :: t
231 HsArrAppType -- higher-order (-<<) or first-order (-<)
232 Bool -- True => right-to-left (f -< arg)
233 -- False => left-to-right (arg >- f)
235 | HsArrForm -- Command formation, (| e cmd1 .. cmdn |)
236 (LHsExpr id) -- the operator
237 -- after type-checking, a type abstraction to be
238 -- applied to the type of the local environment tuple
239 (Maybe Fixity) -- fixity (filled in by the renamer), for forms that
240 -- were converted from OpApp's by the renamer
241 [LHsCmdTop id] -- argument commands
244 ---------------------------------------
245 -- Haskell program coverage (Hpc) Support
248 Int -- module-local tick number
249 [id] -- variables in scope
250 (LHsExpr id) -- sub-expression
253 Int -- module-local tick number for True
254 Int -- module-local tick number for False
255 (LHsExpr id) -- sub-expression
257 | HsTickPragma -- A pragma introduced tick
258 (FastString,(Int,Int),(Int,Int)) -- external span for this tick
261 ---------------------------------------
262 -- These constructors only appear temporarily in the parser.
263 -- The renamer translates them into the Right Thing.
265 | EWildPat -- wildcard
267 | EAsPat (Located id) -- as pattern
270 | EViewPat (LHsExpr id) -- view pattern
273 | ELazyPat (LHsExpr id) -- ~ pattern
275 | HsType (LHsType id) -- Explicit type argument; e.g f {| Int |} x y
277 ---------------------------------------
278 -- Finally, HsWrap appears only in typechecker output
280 | HsWrap HsWrapper -- TRANSLATION
283 type PendingSplice = (Name, LHsExpr Id) -- Typechecked splices, waiting to be
284 -- pasted back in by the desugarer
287 A @Dictionary@, unless of length 0 or 1, becomes a tuple. A
288 @ClassDictLam dictvars methods expr@ is, therefore:
290 \ x -> case x of ( dictvars-and-methods-tuple ) -> expr
294 instance OutputableBndr id => Outputable (HsExpr id) where
295 ppr expr = pprExpr expr
299 -----------------------
300 -- pprExpr, pprLExpr, pprBinds call pprDeeper;
301 -- the underscore versions do not
302 pprLExpr :: OutputableBndr id => LHsExpr id -> SDoc
303 pprLExpr (L _ e) = pprExpr e
305 pprExpr :: OutputableBndr id => HsExpr id -> SDoc
306 pprExpr e | isAtomicHsExpr e || isQuietHsExpr e = ppr_expr e
307 | otherwise = pprDeeper (ppr_expr e)
309 isQuietHsExpr :: HsExpr id -> Bool
310 -- Parentheses do display something, but it gives little info and
311 -- if we go deeper when we go inside them then we get ugly things
313 isQuietHsExpr (HsPar _) = True
314 -- applications don't display anything themselves
315 isQuietHsExpr (HsApp _ _) = True
316 isQuietHsExpr (OpApp _ _ _ _) = True
317 isQuietHsExpr _ = False
319 pprBinds :: (OutputableBndr idL, OutputableBndr idR)
320 => HsLocalBindsLR idL idR -> SDoc
321 pprBinds b = pprDeeper (ppr b)
323 -----------------------
324 ppr_lexpr :: OutputableBndr id => LHsExpr id -> SDoc
325 ppr_lexpr e = ppr_expr (unLoc e)
327 ppr_expr :: OutputableBndr id => HsExpr id -> SDoc
328 ppr_expr (HsVar v) = pprHsVar v
329 ppr_expr (HsIPVar v) = ppr v
330 ppr_expr (HsLit lit) = ppr lit
331 ppr_expr (HsOverLit lit) = ppr lit
332 ppr_expr (HsPar e) = parens (ppr_lexpr e)
334 ppr_expr (HsCoreAnn s e)
335 = vcat [ptext (sLit "HsCoreAnn") <+> ftext s, ppr_lexpr e]
337 ppr_expr (HsApp e1 e2)
338 = let (fun, args) = collect_args e1 [e2] in
339 hang (ppr_lexpr fun) 2 (sep (map pprParendExpr args))
341 collect_args (L _ (HsApp fun arg)) args = collect_args fun (arg:args)
342 collect_args fun args = (fun, args)
344 ppr_expr (OpApp e1 op _ e2)
346 HsVar v -> pp_infixly v
349 pp_e1 = pprDebugParendExpr e1 -- In debug mode, add parens
350 pp_e2 = pprDebugParendExpr e2 -- to make precedence clear
353 = hang (ppr op) 2 (sep [pp_e1, pp_e2])
356 = sep [nest 2 pp_e1, pprHsInfix v, nest 2 pp_e2]
358 ppr_expr (NegApp e _) = char '-' <+> pprDebugParendExpr e
360 ppr_expr (SectionL expr op)
362 HsVar v -> pp_infixly v
365 pp_expr = pprDebugParendExpr expr
367 pp_prefixly = hang (hsep [text " \\ x_ ->", ppr op])
368 4 (hsep [pp_expr, ptext (sLit "x_ )")])
369 pp_infixly v = (sep [pp_expr, pprHsInfix v])
371 ppr_expr (SectionR op expr)
373 HsVar v -> pp_infixly v
376 pp_expr = pprDebugParendExpr expr
378 pp_prefixly = hang (hsep [text "( \\ x_ ->", ppr op, ptext (sLit "x_")])
379 4 ((<>) pp_expr rparen)
381 = (sep [pprHsInfix v, pp_expr])
383 --avoid using PatternSignatures for stage1 code portability
384 ppr_expr exprType@(HsLam matches)
385 = pprMatches (LambdaExpr `asTypeOf` idType exprType) matches
386 where idType :: HsExpr id -> HsMatchContext id; idType = undefined
388 ppr_expr exprType@(HsCase expr matches)
389 = sep [ sep [ptext (sLit "case"), nest 4 (ppr expr), ptext (sLit "of {")],
390 nest 2 (pprMatches (CaseAlt `asTypeOf` idType exprType) matches <+> char '}') ]
391 where idType :: HsExpr id -> HsMatchContext id; idType = undefined
393 ppr_expr (HsIf e1 e2 e3)
394 = sep [hsep [ptext (sLit "if"), nest 2 (ppr e1), ptext (sLit "then")],
399 -- special case: let ... in let ...
400 ppr_expr (HsLet binds expr@(L _ (HsLet _ _)))
401 = sep [hang (ptext (sLit "let")) 2 (hsep [pprBinds binds, ptext (sLit "in")]),
404 ppr_expr (HsLet binds expr)
405 = sep [hang (ptext (sLit "let")) 2 (pprBinds binds),
406 hang (ptext (sLit "in")) 2 (ppr expr)]
408 ppr_expr (HsDo do_or_list_comp stmts body _) = pprDo do_or_list_comp stmts body
410 ppr_expr (ExplicitList _ exprs)
411 = brackets (pprDeeperList fsep (punctuate comma (map ppr_lexpr exprs)))
413 ppr_expr (ExplicitPArr _ exprs)
414 = pa_brackets (pprDeeperList fsep (punctuate comma (map ppr_lexpr exprs)))
416 ppr_expr (ExplicitTuple exprs boxity)
417 = tupleParens boxity (sep (punctuate comma (map ppr_lexpr exprs)))
419 ppr_expr (RecordCon con_id _ rbinds)
420 = hang (ppr con_id) 2 (ppr rbinds)
422 ppr_expr (RecordUpd aexp rbinds _ _ _)
423 = hang (pprParendExpr aexp) 2 (ppr rbinds)
425 ppr_expr (ExprWithTySig expr sig)
426 = hang (nest 2 (ppr_lexpr expr) <+> dcolon)
428 ppr_expr (ExprWithTySigOut expr sig)
429 = hang (nest 2 (ppr_lexpr expr) <+> dcolon)
432 ppr_expr (ArithSeq _ info) = brackets (ppr info)
433 ppr_expr (PArrSeq _ info) = pa_brackets (ppr info)
435 ppr_expr EWildPat = char '_'
436 ppr_expr (ELazyPat e) = char '~' <> pprParendExpr e
437 ppr_expr (EAsPat v e) = ppr v <> char '@' <> pprParendExpr e
438 ppr_expr (EViewPat p e) = ppr p <+> ptext (sLit "->") <+> ppr e
440 ppr_expr (HsSCC lbl expr)
441 = sep [ ptext (sLit "_scc_") <+> doubleQuotes (ftext lbl),
444 ppr_expr (HsWrap co_fn e) = pprHsWrapper (pprExpr e) co_fn
445 ppr_expr (HsType id) = ppr id
447 ppr_expr (HsSpliceE s) = pprSplice s
448 ppr_expr (HsBracket b) = pprHsBracket b
449 ppr_expr (HsBracketOut e []) = ppr e
450 ppr_expr (HsBracketOut e ps) = ppr e $$ ptext (sLit "pending") <+> ppr ps
451 ppr_expr (HsQuasiQuoteE qq) = ppr qq
453 ppr_expr (HsProc pat (L _ (HsCmdTop cmd _ _ _)))
454 = hsep [ptext (sLit "proc"), ppr pat, ptext (sLit "->"), ppr cmd]
456 ppr_expr (HsTick tickId vars exp)
457 = hcat [ptext (sLit "tick<"),
460 hsep (map pprHsVar vars),
463 ppr_expr (HsBinTick tickIdTrue tickIdFalse exp)
464 = hcat [ptext (sLit "bintick<"),
469 ppr exp,ptext (sLit ")")]
470 ppr_expr (HsTickPragma externalSrcLoc exp)
471 = hcat [ptext (sLit "tickpragma<"),
477 ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp True)
478 = hsep [ppr_lexpr arrow, ptext (sLit "-<"), ppr_lexpr arg]
479 ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp False)
480 = hsep [ppr_lexpr arg, ptext (sLit ">-"), ppr_lexpr arrow]
481 ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp True)
482 = hsep [ppr_lexpr arrow, ptext (sLit "-<<"), ppr_lexpr arg]
483 ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp False)
484 = hsep [ppr_lexpr arg, ptext (sLit ">>-"), ppr_lexpr arrow]
486 ppr_expr (HsArrForm (L _ (HsVar v)) (Just _) [arg1, arg2])
487 = sep [pprCmdArg (unLoc arg1), hsep [pprHsInfix v, pprCmdArg (unLoc arg2)]]
488 ppr_expr (HsArrForm op _ args)
489 = hang (ptext (sLit "(|") <> ppr_lexpr op)
490 4 (sep (map (pprCmdArg.unLoc) args) <> ptext (sLit "|)"))
492 pprCmdArg :: OutputableBndr id => HsCmdTop id -> SDoc
493 pprCmdArg (HsCmdTop cmd@(L _ (HsArrForm _ Nothing [])) _ _ _)
495 pprCmdArg (HsCmdTop cmd _ _ _)
496 = parens (ppr_lexpr cmd)
498 instance OutputableBndr id => Outputable (HsCmdTop id) where
501 -- add parallel array brackets around a document
503 pa_brackets :: SDoc -> SDoc
504 pa_brackets p = ptext (sLit "[:") <> p <> ptext (sLit ":]")
507 HsSyn records exactly where the user put parens, with HsPar.
508 So generally speaking we print without adding any parens.
509 However, some code is internally generated, and in some places
510 parens are absolutely required; so for these places we use
511 pprParendExpr (but don't print double parens of course).
513 For operator applications we don't add parens, because the oprerator
514 fixities should do the job, except in debug mode (-dppr-debug) so we
515 can see the structure of the parse tree.
518 pprDebugParendExpr :: OutputableBndr id => LHsExpr id -> SDoc
519 pprDebugParendExpr expr
520 = getPprStyle (\sty ->
521 if debugStyle sty then pprParendExpr expr
524 pprParendExpr :: OutputableBndr id => LHsExpr id -> SDoc
527 pp_as_was = pprLExpr expr
528 -- Using pprLExpr makes sure that we go 'deeper'
529 -- I think that is usually (always?) right
533 HsOverLit _ -> pp_as_was
535 HsIPVar _ -> pp_as_was
536 ExplicitList _ _ -> pp_as_was
537 ExplicitPArr _ _ -> pp_as_was
538 ExplicitTuple _ _ -> pp_as_was
540 HsBracket _ -> pp_as_was
541 HsBracketOut _ [] -> pp_as_was
543 | isListCompExpr sc -> pp_as_was
544 _ -> parens pp_as_was
546 isAtomicHsExpr :: HsExpr id -> Bool -- A single token
547 isAtomicHsExpr (HsVar {}) = True
548 isAtomicHsExpr (HsLit {}) = True
549 isAtomicHsExpr (HsOverLit {}) = True
550 isAtomicHsExpr (HsIPVar {}) = True
551 isAtomicHsExpr (HsWrap _ e) = isAtomicHsExpr e
552 isAtomicHsExpr (HsPar e) = isAtomicHsExpr (unLoc e)
553 isAtomicHsExpr _ = False
556 %************************************************************************
558 \subsection{Commands (in arrow abstractions)}
560 %************************************************************************
562 We re-use HsExpr to represent these.
565 type HsCmd id = HsExpr id
567 type LHsCmd id = LHsExpr id
569 data HsArrAppType = HsHigherOrderApp | HsFirstOrderApp
572 The legal constructors for commands are:
574 = HsArrApp ... -- as above
576 | HsArrForm ... -- as above
581 | HsLam (Match id) -- kappa
583 -- the renamer turns this one into HsArrForm
584 | OpApp (HsExpr id) -- left operand
585 (HsCmd id) -- operator
586 Fixity -- Renamer adds fixity; bottom until then
587 (HsCmd id) -- right operand
589 | HsPar (HsCmd id) -- parenthesised command
592 [Match id] -- bodies are HsCmd's
595 | HsIf (HsExpr id) -- predicate
596 (HsCmd id) -- then part
597 (HsCmd id) -- else part
600 | HsLet (HsLocalBinds id) -- let(rec)
603 | HsDo (HsStmtContext Name) -- The parameterisation is unimportant
604 -- because in this context we never use
605 -- the PatGuard or ParStmt variant
606 [Stmt id] -- HsExpr's are really HsCmd's
607 PostTcType -- Type of the whole expression
610 Top-level command, introducing a new arrow.
611 This may occur inside a proc (where the stack is empty) or as an
612 argument of a command-forming operator.
615 type LHsCmdTop id = Located (HsCmdTop id)
618 = HsCmdTop (LHsCmd id)
619 [PostTcType] -- types of inputs on the command's stack
620 PostTcType -- return type of the command
621 (SyntaxTable id) -- after type checking:
622 -- names used in the command's desugaring
625 %************************************************************************
627 \subsection{Record binds}
629 %************************************************************************
632 type HsRecordBinds id = HsRecFields id (LHsExpr id)
637 %************************************************************************
639 \subsection{@Match@, @GRHSs@, and @GRHS@ datatypes}
641 %************************************************************************
643 @Match@es are sets of pattern bindings and right hand sides for
644 functions, patterns or case branches. For example, if a function @g@
650 then \tr{g} has two @Match@es: @(x,y) = y@ and @((x:ys),y) = y+1@.
652 It is always the case that each element of an @[Match]@ list has the
653 same number of @pats@s inside it. This corresponds to saying that
654 a function defined by pattern matching must have the same number of
655 patterns in each equation.
660 [LMatch id] -- The alternatives
661 PostTcType -- The type is the type of the entire group
662 -- t1 -> ... -> tn -> tr
663 -- where there are n patterns
665 type LMatch id = Located (Match id)
669 [LPat id] -- The patterns
670 (Maybe (LHsType id)) -- A type signature for the result of the match
671 -- Nothing after typechecking
674 isEmptyMatchGroup :: MatchGroup id -> Bool
675 isEmptyMatchGroup (MatchGroup ms _) = null ms
677 matchGroupArity :: MatchGroup id -> Arity
678 matchGroupArity (MatchGroup [] _)
679 = panic "matchGroupArity" -- Precondition: MatchGroup is non-empty
680 matchGroupArity (MatchGroup (match:matches) _)
681 = ASSERT( all ((== n_pats) . length . hsLMatchPats) matches )
682 -- Assertion just checks that all the matches have the same number of pats
685 n_pats = length (hsLMatchPats match)
687 hsLMatchPats :: LMatch id -> [LPat id]
688 hsLMatchPats (L _ (Match pats _ _)) = pats
690 -- | GRHSs are used both for pattern bindings and for Matches
693 grhssGRHSs :: [LGRHS id], -- ^ Guarded RHSs
694 grhssLocalBinds :: (HsLocalBinds id) -- ^ The where clause
697 type LGRHS id = Located (GRHS id)
699 -- | Guarded Right Hand Side.
700 data GRHS id = GRHS [LStmt id] -- Guards
701 (LHsExpr id) -- Right hand side
704 We know the list must have at least one @Match@ in it.
707 pprMatches :: (OutputableBndr idL, OutputableBndr idR) => HsMatchContext idL -> MatchGroup idR -> SDoc
708 pprMatches ctxt (MatchGroup matches _)
709 = vcat (map (pprMatch ctxt) (map unLoc matches))
710 -- Don't print the type; it's only a place-holder before typechecking
712 -- Exported to HsBinds, which can't see the defn of HsMatchContext
713 pprFunBind :: (OutputableBndr idL, OutputableBndr idR) => idL -> Bool -> MatchGroup idR -> SDoc
714 pprFunBind fun inf matches = pprMatches (FunRhs fun inf) matches
716 -- Exported to HsBinds, which can't see the defn of HsMatchContext
717 pprPatBind :: (OutputableBndr bndr, OutputableBndr id)
718 => LPat bndr -> GRHSs id -> SDoc
719 pprPatBind pat ty@(grhss)
720 = sep [ppr pat, nest 4 (pprGRHSs (PatBindRhs `asTypeOf` idType ty) grhss)]
721 --avoid using PatternSignatures for stage1 code portability
722 where idType :: GRHSs id -> HsMatchContext id; idType = undefined
725 pprMatch :: (OutputableBndr idL, OutputableBndr idR) => HsMatchContext idL -> Match idR -> SDoc
726 pprMatch ctxt (Match pats maybe_ty grhss)
727 = herald <+> sep [sep (map ppr other_pats),
729 nest 2 (pprGRHSs ctxt grhss)]
734 | not is_infix -> (ppr fun, pats)
736 -- Not pprBndr; the AbsBinds will
737 -- have printed the signature
739 | null pats3 -> (pp_infix, [])
742 | otherwise -> (parens pp_infix, pats3)
745 (pat1:pat2:pats3) = pats
746 pp_infix = ppr pat1 <+> ppr fun <+> ppr pat2
748 LambdaExpr -> (char '\\', pats)
751 ppr_maybe_ty = case maybe_ty of
752 Just ty -> dcolon <+> ppr ty
756 pprGRHSs :: (OutputableBndr idL, OutputableBndr idR)
757 => HsMatchContext idL -> GRHSs idR -> SDoc
758 pprGRHSs ctxt (GRHSs grhss binds)
759 = vcat (map (pprGRHS ctxt . unLoc) grhss)
760 $$ if isEmptyLocalBinds binds then empty
761 else text "where" $$ nest 4 (pprBinds binds)
763 pprGRHS :: (OutputableBndr idL, OutputableBndr idR)
764 => HsMatchContext idL -> GRHS idR -> SDoc
766 pprGRHS ctxt (GRHS [] expr)
769 pprGRHS ctxt (GRHS guards expr)
770 = sep [char '|' <+> interpp'SP guards, pp_rhs ctxt expr]
772 pp_rhs :: OutputableBndr idR => HsMatchContext idL -> LHsExpr idR -> SDoc
773 pp_rhs ctxt rhs = matchSeparator ctxt <+> pprDeeper (ppr rhs)
776 %************************************************************************
778 \subsection{Do stmts and list comprehensions}
780 %************************************************************************
783 type LStmt id = Located (StmtLR id id)
784 type LStmtLR idL idR = Located (StmtLR idL idR)
786 type Stmt id = StmtLR id id
788 data GroupByClause id
789 = GroupByNothing (LHsExpr id) -- Using expression, i.e.
790 -- "then group using f" ==> GroupByNothing f
791 | GroupBySomething (Either (LHsExpr id) (SyntaxExpr id)) (LHsExpr id)
792 -- "then group using f by e" ==> GroupBySomething (Left f) e
793 -- "then group by e" ==> GroupBySomething (Right _) e: in
794 -- this case the expression is filled
797 -- The SyntaxExprs in here are used *only* for do-notation, which
798 -- has rebindable syntax. Otherwise they are unused.
800 = BindStmt (LPat idL)
802 (SyntaxExpr idR) -- The (>>=) operator
803 (SyntaxExpr idR) -- The fail operator
804 -- The fail operator is noSyntaxExpr
805 -- if the pattern match can't fail
807 | ExprStmt (LHsExpr idR)
808 (SyntaxExpr idR) -- The (>>) operator
809 PostTcType -- Element type of the RHS (used for arrows)
811 | LetStmt (HsLocalBindsLR idL idR)
813 -- ParStmts only occur in a list comprehension
814 | ParStmt [([LStmt idL], [idR])]
815 -- After renaming, the ids are the binders bound by the stmts and used
818 | TransformStmt ([LStmt idL], [idR]) (LHsExpr idR) (Maybe (LHsExpr idR))
819 -- After renaming, the IDs are the binders occurring within this
820 -- transform statement that are used after it
821 -- "qs, then f by e" ==> TransformStmt (qs, binders) f (Just e)
822 -- "qs, then f" ==> TransformStmt (qs, binders) f Nothing
824 | GroupStmt ([LStmt idL], [(idR, idR)]) (GroupByClause idR)
825 -- After renaming, the IDs are the binders occurring within this
826 -- transform statement that are used after it which are paired with
827 -- the names which they group over in statements
829 -- Recursive statement (see Note [RecStmt] below)
830 | RecStmt [LStmtLR idL idR]
831 --- The next two fields are only valid after renaming
832 [idR] -- The ids are a subset of the variables bound by the
833 -- stmts that are used in stmts that follow the RecStmt
835 [idR] -- Ditto, but these variables are the "recursive" ones,
836 -- that are used before they are bound in the stmts of
837 -- the RecStmt. From a type-checking point of view,
838 -- these ones have to be monomorphic
840 --- These fields are only valid after typechecking
841 [PostTcExpr] -- These expressions correspond 1-to-1 with
842 -- the "recursive" [id], and are the
843 -- expressions that should be returned by
845 -- They may not quite be the Ids themselves,
846 -- because the Id may be *polymorphic*, but
847 -- the returned thing has to be *monomorphic*.
848 (DictBinds idR) -- Method bindings of Ids bound by the
849 -- RecStmt, and used afterwards
852 ExprStmts are a bit tricky, because what they mean
853 depends on the context. Consider the following contexts:
855 A do expression of type (m res_ty)
856 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
857 * ExprStmt E any_ty: do { ....; E; ... }
859 Translation: E >> ...
861 A list comprehensions of type [elt_ty]
862 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
863 * ExprStmt E Bool: [ .. | .... E ]
865 [ .. | .... | ..., E | ... ]
867 Translation: if E then fail else ...
869 A guard list, guarding a RHS of type rhs_ty
870 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
871 * ExprStmt E Bool: f x | ..., E, ... = ...rhs...
873 Translation: if E then fail else ...
875 Array comprehensions are handled like list comprehensions -=chak
882 , RecStmt [a::forall a. a -> a, b]
884 [ BindStmt b (return x)
890 Here, the RecStmt binds a,b,c; but
891 - Only a,b are used in the stmts *following* the RecStmt,
892 This 'a' is *polymorphic'
893 - Only a,c are used in the stmts *inside* the RecStmt
894 *before* their bindings
895 This 'a' is monomorphic
897 Nota Bene: the two a's have different types, even though they
902 instance (OutputableBndr idL, OutputableBndr idR) => Outputable (StmtLR idL idR) where
903 ppr stmt = pprStmt stmt
905 pprStmt :: (OutputableBndr idL, OutputableBndr idR) => (StmtLR idL idR) -> SDoc
906 pprStmt (BindStmt pat expr _ _) = hsep [ppr pat, ptext (sLit "<-"), ppr expr]
907 pprStmt (LetStmt binds) = hsep [ptext (sLit "let"), pprBinds binds]
908 pprStmt (ExprStmt expr _ _) = ppr expr
909 pprStmt (ParStmt stmtss) = hsep (map doStmts stmtss)
910 where doStmts stmts = ptext (sLit "| ") <> ppr stmts
911 pprStmt (TransformStmt (stmts, _) usingExpr maybeByExpr)
912 = (hsep [stmtsDoc, ptext (sLit "then"), ppr usingExpr, byExprDoc])
913 where stmtsDoc = interpp'SP stmts
914 byExprDoc = maybe empty (\byExpr -> hsep [ptext (sLit "by"), ppr byExpr]) maybeByExpr
915 pprStmt (GroupStmt (stmts, _) groupByClause) = (hsep [stmtsDoc, ptext (sLit "then group"), pprGroupByClause groupByClause])
916 where stmtsDoc = interpp'SP stmts
917 pprStmt (RecStmt segment _ _ _ _) = ptext (sLit "rec") <+> braces (vcat (map ppr segment))
919 pprGroupByClause :: (OutputableBndr id) => GroupByClause id -> SDoc
920 pprGroupByClause (GroupByNothing usingExpr) = hsep [ptext (sLit "using"), ppr usingExpr]
921 pprGroupByClause (GroupBySomething eitherUsingExpr byExpr) = hsep [ptext (sLit "by"), ppr byExpr, usingExprDoc]
922 where usingExprDoc = either (\usingExpr -> hsep [ptext (sLit "using"), ppr usingExpr]) (const empty) eitherUsingExpr
924 pprDo :: OutputableBndr id => HsStmtContext any -> [LStmt id] -> LHsExpr id -> SDoc
925 pprDo DoExpr stmts body = ptext (sLit "do") <+> pprDeeperList vcat (map ppr stmts ++ [ppr body])
926 pprDo (MDoExpr _) stmts body = ptext (sLit "mdo") <+> pprDeeperList vcat (map ppr stmts ++ [ppr body])
927 pprDo ListComp stmts body = pprComp brackets stmts body
928 pprDo PArrComp stmts body = pprComp pa_brackets stmts body
929 pprDo _ _ _ = panic "pprDo" -- PatGuard, ParStmtCxt
931 pprComp :: OutputableBndr id => (SDoc -> SDoc) -> [LStmt id] -> LHsExpr id -> SDoc
932 pprComp brack quals body
934 hang (ppr body <+> char '|')
938 %************************************************************************
940 Template Haskell quotation brackets
942 %************************************************************************
945 data HsSplice id = HsSplice -- $z or $(f 4)
946 id -- The id is just a unique name to
947 (LHsExpr id) -- identify this splice point
949 instance OutputableBndr id => Outputable (HsSplice id) where
952 pprSplice :: OutputableBndr id => HsSplice id -> SDoc
953 pprSplice (HsSplice n e)
954 = char '$' <> ifPprDebug (brackets (ppr n)) <> pprParendExpr e
957 data HsBracket id = ExpBr (LHsExpr id) -- [| expr |]
958 | PatBr (LPat id) -- [p| pat |]
959 | DecBr (HsGroup id) -- [d| decls |]
960 | TypBr (LHsType id) -- [t| type |]
961 | VarBr id -- 'x, ''T
963 instance OutputableBndr id => Outputable (HsBracket id) where
967 pprHsBracket :: OutputableBndr id => HsBracket id -> SDoc
968 pprHsBracket (ExpBr e) = thBrackets empty (ppr e)
969 pprHsBracket (PatBr p) = thBrackets (char 'p') (ppr p)
970 pprHsBracket (DecBr d) = thBrackets (char 'd') (ppr d)
971 pprHsBracket (TypBr t) = thBrackets (char 't') (ppr t)
972 pprHsBracket (VarBr n) = char '\'' <> ppr n
973 -- Infelicity: can't show ' vs '', because
974 -- we can't ask n what its OccName is, because the
975 -- pretty-printer for HsExpr doesn't ask for NamedThings
976 -- But the pretty-printer for names will show the OccName class
978 thBrackets :: SDoc -> SDoc -> SDoc
979 thBrackets pp_kind pp_body = char '[' <> pp_kind <> char '|' <+>
980 pp_body <+> ptext (sLit "|]")
983 %************************************************************************
985 \subsection{Enumerations and list comprehensions}
987 %************************************************************************
992 | FromThen (LHsExpr id)
994 | FromTo (LHsExpr id)
996 | FromThenTo (LHsExpr id)
1002 instance OutputableBndr id => Outputable (ArithSeqInfo id) where
1003 ppr (From e1) = hcat [ppr e1, pp_dotdot]
1004 ppr (FromThen e1 e2) = hcat [ppr e1, comma, space, ppr e2, pp_dotdot]
1005 ppr (FromTo e1 e3) = hcat [ppr e1, pp_dotdot, ppr e3]
1006 ppr (FromThenTo e1 e2 e3)
1007 = hcat [ppr e1, comma, space, ppr e2, pp_dotdot, ppr e3]
1010 pp_dotdot = ptext (sLit " .. ")
1014 %************************************************************************
1016 \subsection{HsMatchCtxt}
1018 %************************************************************************
1021 data HsMatchContext id -- Context of a Match
1022 = FunRhs id Bool -- Function binding for f; True <=> written infix
1023 | CaseAlt -- Patterns and guards on a case alternative
1024 | LambdaExpr -- Patterns of a lambda
1025 | ProcExpr -- Patterns of a proc
1026 | PatBindRhs -- Patterns in the *guards* of a pattern binding
1027 | RecUpd -- Record update [used only in DsExpr to
1028 -- tell matchWrapper what sort of
1029 -- runtime error message to generate]
1030 | StmtCtxt (HsStmtContext id) -- Pattern of a do-stmt or list comprehension
1033 data HsStmtContext id
1036 | MDoExpr PostTcTable -- Recursive do-expression
1037 -- (tiresomely, it needs table
1038 -- of its return/bind ops)
1039 | PArrComp -- Parallel array comprehension
1040 | PatGuard (HsMatchContext id) -- Pattern guard for specified thing
1041 | ParStmtCtxt (HsStmtContext id) -- A branch of a parallel stmt
1042 | TransformStmtCtxt (HsStmtContext id) -- A branch of a transform stmt
1046 isDoExpr :: HsStmtContext id -> Bool
1047 isDoExpr DoExpr = True
1048 isDoExpr (MDoExpr _) = True
1051 isListCompExpr :: HsStmtContext id -> Bool
1052 isListCompExpr ListComp = True
1053 isListCompExpr PArrComp = True
1054 isListCompExpr _ = False
1058 matchSeparator :: HsMatchContext id -> SDoc
1059 matchSeparator (FunRhs {}) = ptext (sLit "=")
1060 matchSeparator CaseAlt = ptext (sLit "->")
1061 matchSeparator LambdaExpr = ptext (sLit "->")
1062 matchSeparator ProcExpr = ptext (sLit "->")
1063 matchSeparator PatBindRhs = ptext (sLit "=")
1064 matchSeparator (StmtCtxt _) = ptext (sLit "<-")
1065 matchSeparator RecUpd = panic "unused"
1069 pprMatchContext :: Outputable id => HsMatchContext id -> SDoc
1070 pprMatchContext (FunRhs fun _) = ptext (sLit "the definition of")
1071 <+> quotes (ppr fun)
1072 pprMatchContext CaseAlt = ptext (sLit "a case alternative")
1073 pprMatchContext RecUpd = ptext (sLit "a record-update construct")
1074 pprMatchContext PatBindRhs = ptext (sLit "a pattern binding")
1075 pprMatchContext LambdaExpr = ptext (sLit "a lambda abstraction")
1076 pprMatchContext ProcExpr = ptext (sLit "an arrow abstraction")
1077 pprMatchContext (StmtCtxt ctxt) = ptext (sLit "a pattern binding in")
1078 $$ pprStmtContext ctxt
1080 pprStmtContext :: Outputable id => HsStmtContext id -> SDoc
1081 pprStmtContext (ParStmtCtxt c)
1082 = sep [ptext (sLit "a parallel branch of"), pprStmtContext c]
1083 pprStmtContext (TransformStmtCtxt c)
1084 = sep [ptext (sLit "a transformed branch of"), pprStmtContext c]
1085 pprStmtContext (PatGuard ctxt)
1086 = ptext (sLit "a pattern guard for") $$ pprMatchContext ctxt
1087 pprStmtContext DoExpr = ptext (sLit "a 'do' expression")
1088 pprStmtContext (MDoExpr _) = ptext (sLit "an 'mdo' expression")
1089 pprStmtContext ListComp = ptext (sLit "a list comprehension")
1090 pprStmtContext PArrComp = ptext (sLit "an array comprehension")
1093 pprMatchRhsContext (FunRhs fun) = ptext (sLit "a right-hand side of function") <+> quotes (ppr fun)
1094 pprMatchRhsContext CaseAlt = ptext (sLit "the body of a case alternative")
1095 pprMatchRhsContext PatBindRhs = ptext (sLit "the right-hand side of a pattern binding")
1096 pprMatchRhsContext LambdaExpr = ptext (sLit "the body of a lambda")
1097 pprMatchRhsContext ProcExpr = ptext (sLit "the body of a proc")
1098 pprMatchRhsContext other = panic "pprMatchRhsContext" -- RecUpd, StmtCtxt
1100 -- Used for the result statement of comprehension
1101 -- e.g. the 'e' in [ e | ... ]
1102 -- or the 'r' in f x = r
1103 pprStmtResultContext (PatGuard ctxt) = pprMatchRhsContext ctxt
1104 pprStmtResultContext other = ptext (sLit "the result of") <+> pprStmtContext other
1107 -- Used to generate the string for a *runtime* error message
1108 matchContextErrString :: Outputable id => HsMatchContext id -> String
1109 matchContextErrString (FunRhs fun _) = "function " ++ showSDoc (ppr fun)
1110 matchContextErrString CaseAlt = "case"
1111 matchContextErrString PatBindRhs = "pattern binding"
1112 matchContextErrString RecUpd = "record update"
1113 matchContextErrString LambdaExpr = "lambda"
1114 matchContextErrString ProcExpr = "proc"
1115 matchContextErrString (StmtCtxt (ParStmtCtxt c)) = matchContextErrString (StmtCtxt c)
1116 matchContextErrString (StmtCtxt (TransformStmtCtxt c)) = matchContextErrString (StmtCtxt c)
1117 matchContextErrString (StmtCtxt (PatGuard _)) = "pattern guard"
1118 matchContextErrString (StmtCtxt DoExpr) = "'do' expression"
1119 matchContextErrString (StmtCtxt (MDoExpr _)) = "'mdo' expression"
1120 matchContextErrString (StmtCtxt ListComp) = "list comprehension"
1121 matchContextErrString (StmtCtxt PArrComp) = "array comprehension"
1125 pprMatchInCtxt :: (OutputableBndr idL, OutputableBndr idR)
1126 => HsMatchContext idL -> Match idR -> SDoc
1127 pprMatchInCtxt ctxt match = hang (ptext (sLit "In") <+> pprMatchContext ctxt <> colon)
1128 4 (pprMatch ctxt match)
1130 pprStmtInCtxt :: (OutputableBndr idL, OutputableBndr idR)
1131 => HsStmtContext idL -> StmtLR idL idR -> SDoc
1132 pprStmtInCtxt ctxt stmt = hang (ptext (sLit "In a stmt of") <+> pprStmtContext ctxt <> colon)