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
532 ArithSeq{} -> pp_as_was
533 PArrSeq{} -> pp_as_was
535 HsOverLit _ -> pp_as_was
537 HsIPVar _ -> pp_as_was
538 ExplicitList _ _ -> pp_as_was
539 ExplicitPArr _ _ -> pp_as_was
540 ExplicitTuple _ _ -> pp_as_was
542 HsBracket _ -> pp_as_was
543 HsBracketOut _ [] -> pp_as_was
545 | isListCompExpr sc -> pp_as_was
546 _ -> parens pp_as_was
548 isAtomicHsExpr :: HsExpr id -> Bool -- A single token
549 isAtomicHsExpr (HsVar {}) = True
550 isAtomicHsExpr (HsLit {}) = True
551 isAtomicHsExpr (HsOverLit {}) = True
552 isAtomicHsExpr (HsIPVar {}) = True
553 isAtomicHsExpr (HsWrap _ e) = isAtomicHsExpr e
554 isAtomicHsExpr (HsPar e) = isAtomicHsExpr (unLoc e)
555 isAtomicHsExpr _ = False
558 %************************************************************************
560 \subsection{Commands (in arrow abstractions)}
562 %************************************************************************
564 We re-use HsExpr to represent these.
567 type HsCmd id = HsExpr id
569 type LHsCmd id = LHsExpr id
571 data HsArrAppType = HsHigherOrderApp | HsFirstOrderApp
574 The legal constructors for commands are:
576 = HsArrApp ... -- as above
578 | HsArrForm ... -- as above
583 | HsLam (Match id) -- kappa
585 -- the renamer turns this one into HsArrForm
586 | OpApp (HsExpr id) -- left operand
587 (HsCmd id) -- operator
588 Fixity -- Renamer adds fixity; bottom until then
589 (HsCmd id) -- right operand
591 | HsPar (HsCmd id) -- parenthesised command
594 [Match id] -- bodies are HsCmd's
597 | HsIf (HsExpr id) -- predicate
598 (HsCmd id) -- then part
599 (HsCmd id) -- else part
602 | HsLet (HsLocalBinds id) -- let(rec)
605 | HsDo (HsStmtContext Name) -- The parameterisation is unimportant
606 -- because in this context we never use
607 -- the PatGuard or ParStmt variant
608 [Stmt id] -- HsExpr's are really HsCmd's
609 PostTcType -- Type of the whole expression
612 Top-level command, introducing a new arrow.
613 This may occur inside a proc (where the stack is empty) or as an
614 argument of a command-forming operator.
617 type LHsCmdTop id = Located (HsCmdTop id)
620 = HsCmdTop (LHsCmd id)
621 [PostTcType] -- types of inputs on the command's stack
622 PostTcType -- return type of the command
623 (SyntaxTable id) -- after type checking:
624 -- names used in the command's desugaring
627 %************************************************************************
629 \subsection{Record binds}
631 %************************************************************************
634 type HsRecordBinds id = HsRecFields id (LHsExpr id)
639 %************************************************************************
641 \subsection{@Match@, @GRHSs@, and @GRHS@ datatypes}
643 %************************************************************************
645 @Match@es are sets of pattern bindings and right hand sides for
646 functions, patterns or case branches. For example, if a function @g@
652 then \tr{g} has two @Match@es: @(x,y) = y@ and @((x:ys),y) = y+1@.
654 It is always the case that each element of an @[Match]@ list has the
655 same number of @pats@s inside it. This corresponds to saying that
656 a function defined by pattern matching must have the same number of
657 patterns in each equation.
662 [LMatch id] -- The alternatives
663 PostTcType -- The type is the type of the entire group
664 -- t1 -> ... -> tn -> tr
665 -- where there are n patterns
667 type LMatch id = Located (Match id)
671 [LPat id] -- The patterns
672 (Maybe (LHsType id)) -- A type signature for the result of the match
673 -- Nothing after typechecking
676 isEmptyMatchGroup :: MatchGroup id -> Bool
677 isEmptyMatchGroup (MatchGroup ms _) = null ms
679 matchGroupArity :: MatchGroup id -> Arity
680 matchGroupArity (MatchGroup [] _)
681 = panic "matchGroupArity" -- Precondition: MatchGroup is non-empty
682 matchGroupArity (MatchGroup (match:matches) _)
683 = ASSERT( all ((== n_pats) . length . hsLMatchPats) matches )
684 -- Assertion just checks that all the matches have the same number of pats
687 n_pats = length (hsLMatchPats match)
689 hsLMatchPats :: LMatch id -> [LPat id]
690 hsLMatchPats (L _ (Match pats _ _)) = pats
692 -- | GRHSs are used both for pattern bindings and for Matches
695 grhssGRHSs :: [LGRHS id], -- ^ Guarded RHSs
696 grhssLocalBinds :: (HsLocalBinds id) -- ^ The where clause
699 type LGRHS id = Located (GRHS id)
701 -- | Guarded Right Hand Side.
702 data GRHS id = GRHS [LStmt id] -- Guards
703 (LHsExpr id) -- Right hand side
706 We know the list must have at least one @Match@ in it.
709 pprMatches :: (OutputableBndr idL, OutputableBndr idR) => HsMatchContext idL -> MatchGroup idR -> SDoc
710 pprMatches ctxt (MatchGroup matches _)
711 = vcat (map (pprMatch ctxt) (map unLoc matches))
712 -- Don't print the type; it's only a place-holder before typechecking
714 -- Exported to HsBinds, which can't see the defn of HsMatchContext
715 pprFunBind :: (OutputableBndr idL, OutputableBndr idR) => idL -> Bool -> MatchGroup idR -> SDoc
716 pprFunBind fun inf matches = pprMatches (FunRhs fun inf) matches
718 -- Exported to HsBinds, which can't see the defn of HsMatchContext
719 pprPatBind :: (OutputableBndr bndr, OutputableBndr id)
720 => LPat bndr -> GRHSs id -> SDoc
721 pprPatBind pat ty@(grhss)
722 = sep [ppr pat, nest 4 (pprGRHSs (PatBindRhs `asTypeOf` idType ty) grhss)]
723 --avoid using PatternSignatures for stage1 code portability
724 where idType :: GRHSs id -> HsMatchContext id; idType = undefined
727 pprMatch :: (OutputableBndr idL, OutputableBndr idR) => HsMatchContext idL -> Match idR -> SDoc
728 pprMatch ctxt (Match pats maybe_ty grhss)
729 = herald <+> sep [sep (map ppr other_pats),
731 nest 2 (pprGRHSs ctxt grhss)]
736 | not is_infix -> (ppr fun, pats)
738 -- Not pprBndr; the AbsBinds will
739 -- have printed the signature
741 | null pats3 -> (pp_infix, [])
744 | otherwise -> (parens pp_infix, pats3)
747 (pat1:pat2:pats3) = pats
748 pp_infix = ppr pat1 <+> ppr fun <+> ppr pat2
750 LambdaExpr -> (char '\\', pats)
753 ppr_maybe_ty = case maybe_ty of
754 Just ty -> dcolon <+> ppr ty
758 pprGRHSs :: (OutputableBndr idL, OutputableBndr idR)
759 => HsMatchContext idL -> GRHSs idR -> SDoc
760 pprGRHSs ctxt (GRHSs grhss binds)
761 = vcat (map (pprGRHS ctxt . unLoc) grhss)
762 $$ if isEmptyLocalBinds binds then empty
763 else text "where" $$ nest 4 (pprBinds binds)
765 pprGRHS :: (OutputableBndr idL, OutputableBndr idR)
766 => HsMatchContext idL -> GRHS idR -> SDoc
768 pprGRHS ctxt (GRHS [] expr)
771 pprGRHS ctxt (GRHS guards expr)
772 = sep [char '|' <+> interpp'SP guards, pp_rhs ctxt expr]
774 pp_rhs :: OutputableBndr idR => HsMatchContext idL -> LHsExpr idR -> SDoc
775 pp_rhs ctxt rhs = matchSeparator ctxt <+> pprDeeper (ppr rhs)
778 %************************************************************************
780 \subsection{Do stmts and list comprehensions}
782 %************************************************************************
785 type LStmt id = Located (StmtLR id id)
786 type LStmtLR idL idR = Located (StmtLR idL idR)
788 type Stmt id = StmtLR id id
790 data GroupByClause id
791 = GroupByNothing (LHsExpr id) -- Using expression, i.e.
792 -- "then group using f" ==> GroupByNothing f
793 | GroupBySomething (Either (LHsExpr id) (SyntaxExpr id)) (LHsExpr id)
794 -- "then group using f by e" ==> GroupBySomething (Left f) e
795 -- "then group by e" ==> GroupBySomething (Right _) e: in
796 -- this case the expression is filled
799 -- The SyntaxExprs in here are used *only* for do-notation, which
800 -- has rebindable syntax. Otherwise they are unused.
802 = BindStmt (LPat idL)
804 (SyntaxExpr idR) -- The (>>=) operator
805 (SyntaxExpr idR) -- The fail operator
806 -- The fail operator is noSyntaxExpr
807 -- if the pattern match can't fail
809 | ExprStmt (LHsExpr idR)
810 (SyntaxExpr idR) -- The (>>) operator
811 PostTcType -- Element type of the RHS (used for arrows)
813 | LetStmt (HsLocalBindsLR idL idR)
815 -- ParStmts only occur in a list comprehension
816 | ParStmt [([LStmt idL], [idR])]
817 -- After renaming, the ids are the binders bound by the stmts and used
820 | TransformStmt ([LStmt idL], [idR]) (LHsExpr idR) (Maybe (LHsExpr idR))
821 -- After renaming, the IDs are the binders occurring within this
822 -- transform statement that are used after it
823 -- "qs, then f by e" ==> TransformStmt (qs, binders) f (Just e)
824 -- "qs, then f" ==> TransformStmt (qs, binders) f Nothing
826 | GroupStmt ([LStmt idL], [(idR, idR)]) (GroupByClause idR)
827 -- After renaming, the IDs are the binders occurring within this
828 -- transform statement that are used after it which are paired with
829 -- the names which they group over in statements
831 -- Recursive statement (see Note [RecStmt] below)
832 | RecStmt [LStmtLR idL idR]
833 --- The next two fields are only valid after renaming
834 [idR] -- The ids are a subset of the variables bound by the
835 -- stmts that are used in stmts that follow the RecStmt
837 [idR] -- Ditto, but these variables are the "recursive" ones,
838 -- that are used before they are bound in the stmts of
839 -- the RecStmt. From a type-checking point of view,
840 -- these ones have to be monomorphic
842 --- These fields are only valid after typechecking
843 [PostTcExpr] -- These expressions correspond 1-to-1 with
844 -- the "recursive" [id], and are the
845 -- expressions that should be returned by
847 -- They may not quite be the Ids themselves,
848 -- because the Id may be *polymorphic*, but
849 -- the returned thing has to be *monomorphic*.
850 (DictBinds idR) -- Method bindings of Ids bound by the
851 -- RecStmt, and used afterwards
854 ExprStmts are a bit tricky, because what they mean
855 depends on the context. Consider the following contexts:
857 A do expression of type (m res_ty)
858 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
859 * ExprStmt E any_ty: do { ....; E; ... }
861 Translation: E >> ...
863 A list comprehensions of type [elt_ty]
864 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
865 * ExprStmt E Bool: [ .. | .... E ]
867 [ .. | .... | ..., E | ... ]
869 Translation: if E then fail else ...
871 A guard list, guarding a RHS of type rhs_ty
872 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
873 * ExprStmt E Bool: f x | ..., E, ... = ...rhs...
875 Translation: if E then fail else ...
877 Array comprehensions are handled like list comprehensions -=chak
884 , RecStmt [a::forall a. a -> a, b]
886 [ BindStmt b (return x)
892 Here, the RecStmt binds a,b,c; but
893 - Only a,b are used in the stmts *following* the RecStmt,
894 This 'a' is *polymorphic'
895 - Only a,c are used in the stmts *inside* the RecStmt
896 *before* their bindings
897 This 'a' is monomorphic
899 Nota Bene: the two a's have different types, even though they
904 instance (OutputableBndr idL, OutputableBndr idR) => Outputable (StmtLR idL idR) where
905 ppr stmt = pprStmt stmt
907 pprStmt :: (OutputableBndr idL, OutputableBndr idR) => (StmtLR idL idR) -> SDoc
908 pprStmt (BindStmt pat expr _ _) = hsep [ppr pat, ptext (sLit "<-"), ppr expr]
909 pprStmt (LetStmt binds) = hsep [ptext (sLit "let"), pprBinds binds]
910 pprStmt (ExprStmt expr _ _) = ppr expr
911 pprStmt (ParStmt stmtss) = hsep (map doStmts stmtss)
912 where doStmts stmts = ptext (sLit "| ") <> ppr stmts
913 pprStmt (TransformStmt (stmts, _) usingExpr maybeByExpr)
914 = (hsep [stmtsDoc, ptext (sLit "then"), ppr usingExpr, byExprDoc])
915 where stmtsDoc = interpp'SP stmts
916 byExprDoc = maybe empty (\byExpr -> hsep [ptext (sLit "by"), ppr byExpr]) maybeByExpr
917 pprStmt (GroupStmt (stmts, _) groupByClause) = (hsep [stmtsDoc, ptext (sLit "then group"), pprGroupByClause groupByClause])
918 where stmtsDoc = interpp'SP stmts
919 pprStmt (RecStmt segment _ _ _ _) = ptext (sLit "rec") <+> braces (vcat (map ppr segment))
921 pprGroupByClause :: (OutputableBndr id) => GroupByClause id -> SDoc
922 pprGroupByClause (GroupByNothing usingExpr) = hsep [ptext (sLit "using"), ppr usingExpr]
923 pprGroupByClause (GroupBySomething eitherUsingExpr byExpr) = hsep [ptext (sLit "by"), ppr byExpr, usingExprDoc]
924 where usingExprDoc = either (\usingExpr -> hsep [ptext (sLit "using"), ppr usingExpr]) (const empty) eitherUsingExpr
926 pprDo :: OutputableBndr id => HsStmtContext any -> [LStmt id] -> LHsExpr id -> SDoc
927 pprDo DoExpr stmts body = ptext (sLit "do") <+> pprDeeperList vcat (map ppr stmts ++ [ppr body])
928 pprDo (MDoExpr _) stmts body = ptext (sLit "mdo") <+> pprDeeperList vcat (map ppr stmts ++ [ppr body])
929 pprDo ListComp stmts body = pprComp brackets stmts body
930 pprDo PArrComp stmts body = pprComp pa_brackets stmts body
931 pprDo _ _ _ = panic "pprDo" -- PatGuard, ParStmtCxt
933 pprComp :: OutputableBndr id => (SDoc -> SDoc) -> [LStmt id] -> LHsExpr id -> SDoc
934 pprComp brack quals body
936 hang (ppr body <+> char '|')
940 %************************************************************************
942 Template Haskell quotation brackets
944 %************************************************************************
947 data HsSplice id = HsSplice -- $z or $(f 4)
948 id -- The id is just a unique name to
949 (LHsExpr id) -- identify this splice point
951 instance OutputableBndr id => Outputable (HsSplice id) where
954 pprSplice :: OutputableBndr id => HsSplice id -> SDoc
955 pprSplice (HsSplice n e)
956 = char '$' <> ifPprDebug (brackets (ppr n)) <> pprParendExpr e
959 data HsBracket id = ExpBr (LHsExpr id) -- [| expr |]
960 | PatBr (LPat id) -- [p| pat |]
961 | DecBr (HsGroup id) -- [d| decls |]
962 | TypBr (LHsType id) -- [t| type |]
963 | VarBr id -- 'x, ''T
965 instance OutputableBndr id => Outputable (HsBracket id) where
969 pprHsBracket :: OutputableBndr id => HsBracket id -> SDoc
970 pprHsBracket (ExpBr e) = thBrackets empty (ppr e)
971 pprHsBracket (PatBr p) = thBrackets (char 'p') (ppr p)
972 pprHsBracket (DecBr d) = thBrackets (char 'd') (ppr d)
973 pprHsBracket (TypBr t) = thBrackets (char 't') (ppr t)
974 pprHsBracket (VarBr n) = char '\'' <> ppr n
975 -- Infelicity: can't show ' vs '', because
976 -- we can't ask n what its OccName is, because the
977 -- pretty-printer for HsExpr doesn't ask for NamedThings
978 -- But the pretty-printer for names will show the OccName class
980 thBrackets :: SDoc -> SDoc -> SDoc
981 thBrackets pp_kind pp_body = char '[' <> pp_kind <> char '|' <+>
982 pp_body <+> ptext (sLit "|]")
985 %************************************************************************
987 \subsection{Enumerations and list comprehensions}
989 %************************************************************************
994 | FromThen (LHsExpr id)
996 | FromTo (LHsExpr id)
998 | FromThenTo (LHsExpr id)
1004 instance OutputableBndr id => Outputable (ArithSeqInfo id) where
1005 ppr (From e1) = hcat [ppr e1, pp_dotdot]
1006 ppr (FromThen e1 e2) = hcat [ppr e1, comma, space, ppr e2, pp_dotdot]
1007 ppr (FromTo e1 e3) = hcat [ppr e1, pp_dotdot, ppr e3]
1008 ppr (FromThenTo e1 e2 e3)
1009 = hcat [ppr e1, comma, space, ppr e2, pp_dotdot, ppr e3]
1012 pp_dotdot = ptext (sLit " .. ")
1016 %************************************************************************
1018 \subsection{HsMatchCtxt}
1020 %************************************************************************
1023 data HsMatchContext id -- Context of a Match
1024 = FunRhs id Bool -- Function binding for f; True <=> written infix
1025 | CaseAlt -- Patterns and guards on a case alternative
1026 | LambdaExpr -- Patterns of a lambda
1027 | ProcExpr -- Patterns of a proc
1028 | PatBindRhs -- Patterns in the *guards* of a pattern binding
1029 | RecUpd -- Record update [used only in DsExpr to
1030 -- tell matchWrapper what sort of
1031 -- runtime error message to generate]
1032 | StmtCtxt (HsStmtContext id) -- Pattern of a do-stmt or list comprehension
1035 data HsStmtContext id
1038 | MDoExpr PostTcTable -- Recursive do-expression
1039 -- (tiresomely, it needs table
1040 -- of its return/bind ops)
1041 | PArrComp -- Parallel array comprehension
1042 | PatGuard (HsMatchContext id) -- Pattern guard for specified thing
1043 | ParStmtCtxt (HsStmtContext id) -- A branch of a parallel stmt
1044 | TransformStmtCtxt (HsStmtContext id) -- A branch of a transform stmt
1048 isDoExpr :: HsStmtContext id -> Bool
1049 isDoExpr DoExpr = True
1050 isDoExpr (MDoExpr _) = True
1053 isListCompExpr :: HsStmtContext id -> Bool
1054 isListCompExpr ListComp = True
1055 isListCompExpr PArrComp = True
1056 isListCompExpr _ = False
1060 matchSeparator :: HsMatchContext id -> SDoc
1061 matchSeparator (FunRhs {}) = ptext (sLit "=")
1062 matchSeparator CaseAlt = ptext (sLit "->")
1063 matchSeparator LambdaExpr = ptext (sLit "->")
1064 matchSeparator ProcExpr = ptext (sLit "->")
1065 matchSeparator PatBindRhs = ptext (sLit "=")
1066 matchSeparator (StmtCtxt _) = ptext (sLit "<-")
1067 matchSeparator RecUpd = panic "unused"
1071 pprMatchContext :: Outputable id => HsMatchContext id -> SDoc
1072 pprMatchContext (FunRhs fun _) = ptext (sLit "the definition of")
1073 <+> quotes (ppr fun)
1074 pprMatchContext CaseAlt = ptext (sLit "a case alternative")
1075 pprMatchContext RecUpd = ptext (sLit "a record-update construct")
1076 pprMatchContext PatBindRhs = ptext (sLit "a pattern binding")
1077 pprMatchContext LambdaExpr = ptext (sLit "a lambda abstraction")
1078 pprMatchContext ProcExpr = ptext (sLit "an arrow abstraction")
1079 pprMatchContext (StmtCtxt ctxt) = ptext (sLit "a pattern binding in")
1080 $$ pprStmtContext ctxt
1082 pprStmtContext :: Outputable id => HsStmtContext id -> SDoc
1083 pprStmtContext (ParStmtCtxt c)
1084 = sep [ptext (sLit "a parallel branch of"), pprStmtContext c]
1085 pprStmtContext (TransformStmtCtxt c)
1086 = sep [ptext (sLit "a transformed branch of"), pprStmtContext c]
1087 pprStmtContext (PatGuard ctxt)
1088 = ptext (sLit "a pattern guard for") $$ pprMatchContext ctxt
1089 pprStmtContext DoExpr = ptext (sLit "a 'do' expression")
1090 pprStmtContext (MDoExpr _) = ptext (sLit "an 'mdo' expression")
1091 pprStmtContext ListComp = ptext (sLit "a list comprehension")
1092 pprStmtContext PArrComp = ptext (sLit "an array comprehension")
1095 pprMatchRhsContext (FunRhs fun) = ptext (sLit "a right-hand side of function") <+> quotes (ppr fun)
1096 pprMatchRhsContext CaseAlt = ptext (sLit "the body of a case alternative")
1097 pprMatchRhsContext PatBindRhs = ptext (sLit "the right-hand side of a pattern binding")
1098 pprMatchRhsContext LambdaExpr = ptext (sLit "the body of a lambda")
1099 pprMatchRhsContext ProcExpr = ptext (sLit "the body of a proc")
1100 pprMatchRhsContext other = panic "pprMatchRhsContext" -- RecUpd, StmtCtxt
1102 -- Used for the result statement of comprehension
1103 -- e.g. the 'e' in [ e | ... ]
1104 -- or the 'r' in f x = r
1105 pprStmtResultContext (PatGuard ctxt) = pprMatchRhsContext ctxt
1106 pprStmtResultContext other = ptext (sLit "the result of") <+> pprStmtContext other
1109 -- Used to generate the string for a *runtime* error message
1110 matchContextErrString :: Outputable id => HsMatchContext id -> SDoc
1111 matchContextErrString (FunRhs fun _) = ptext (sLit "function") <+> ppr fun
1112 matchContextErrString CaseAlt = ptext (sLit "case")
1113 matchContextErrString PatBindRhs = ptext (sLit "pattern binding")
1114 matchContextErrString RecUpd = ptext (sLit "record update")
1115 matchContextErrString LambdaExpr = ptext (sLit "lambda")
1116 matchContextErrString ProcExpr = ptext (sLit "proc")
1117 matchContextErrString (StmtCtxt (ParStmtCtxt c)) = matchContextErrString (StmtCtxt c)
1118 matchContextErrString (StmtCtxt (TransformStmtCtxt c)) = matchContextErrString (StmtCtxt c)
1119 matchContextErrString (StmtCtxt (PatGuard _)) = ptext (sLit "pattern guard")
1120 matchContextErrString (StmtCtxt DoExpr) = ptext (sLit "'do' expression")
1121 matchContextErrString (StmtCtxt (MDoExpr _)) = ptext (sLit "'mdo' expression")
1122 matchContextErrString (StmtCtxt ListComp) = ptext (sLit "list comprehension")
1123 matchContextErrString (StmtCtxt PArrComp) = ptext (sLit "array comprehension")
1127 pprMatchInCtxt :: (OutputableBndr idL, OutputableBndr idR)
1128 => HsMatchContext idL -> Match idR -> SDoc
1129 pprMatchInCtxt ctxt match = hang (ptext (sLit "In") <+> pprMatchContext ctxt <> colon)
1130 4 (pprMatch ctxt match)
1132 pprStmtInCtxt :: (OutputableBndr idL, OutputableBndr idR)
1133 => HsStmtContext idL -> StmtLR idL idR -> SDoc
1134 pprStmtInCtxt ctxt stmt = hang (ptext (sLit "In a stmt of") <+> pprStmtContext ctxt <> colon)