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 | ExplicitTuple -- Used for explicit tuples and sections thereof
128 | HsCase (LHsExpr id)
131 | HsIf (LHsExpr id) -- predicate
132 (LHsExpr id) -- then part
133 (LHsExpr id) -- else part
135 | HsLet (HsLocalBinds id) -- let(rec)
138 | HsDo (HsStmtContext Name) -- The parameterisation is unimportant
139 -- because in this context we never use
140 -- the PatGuard or ParStmt variant
141 [LStmt id] -- "do":one or more stmts
142 (LHsExpr id) -- The body; the last expression in the
143 -- 'do' of [ body | ... ] in a list comp
144 PostTcType -- Type of the whole expression
146 | ExplicitList -- syntactic list
147 PostTcType -- Gives type of components of list
150 | ExplicitPArr -- syntactic parallel array: [:e1, ..., en:]
151 PostTcType -- type of elements of the parallel array
154 -- Record construction
155 | RecordCon (Located id) -- The constructor. After type checking
156 -- it's the dataConWrapId of the constructor
157 PostTcExpr -- Data con Id applied to type args
161 | RecordUpd (LHsExpr id)
163 -- (HsMatchGroup Id) -- Filled in by the type checker to be
164 -- -- a match that does the job
165 [DataCon] -- Filled in by the type checker to the
166 -- _non-empty_ list of DataCons that have
167 -- all the upd'd fields
168 [PostTcType] -- Argument types of *input* record type
169 [PostTcType] -- and *output* record type
170 -- For a type family, the arg types are of the *instance* tycon,
171 -- not the family tycon
173 | ExprWithTySig -- e :: type
177 | ExprWithTySigOut -- TRANSLATION
179 (LHsType Name) -- Retain the signature for
180 -- round-tripping purposes
182 | ArithSeq -- arithmetic sequence
186 | PArrSeq -- arith. sequence for parallel array
187 PostTcExpr -- [:e1..e2:] or [:e1, e2..e3:]
190 | HsSCC FastString -- "set cost centre" SCC pragma
191 (LHsExpr id) -- expr whose cost is to be measured
193 | HsCoreAnn FastString -- hdaume: core annotation
196 -----------------------------------------------------------
197 -- MetaHaskell Extensions
199 | HsBracket (HsBracket id)
201 | HsBracketOut (HsBracket Name) -- Output of the type checker is
203 [PendingSplice] -- renamed expression, plus
204 -- _typechecked_ splices to be
205 -- pasted back in by the desugarer
207 | HsSpliceE (HsSplice id)
209 | HsQuasiQuoteE (HsQuasiQuote id)
210 -- See Note [Quasi-quote overview] in TcSplice
212 -----------------------------------------------------------
213 -- Arrow notation extension
215 | HsProc (LPat id) -- arrow abstraction, proc
216 (LHsCmdTop id) -- body of the abstraction
217 -- always has an empty stack
219 ---------------------------------------
220 -- The following are commands, not expressions proper
222 | HsArrApp -- Arrow tail, or arrow application (f -< arg)
223 (LHsExpr id) -- arrow expression, f
224 (LHsExpr id) -- input expression, arg
225 PostTcType -- type of the arrow expressions f,
226 -- of the form a t t', where arg :: t
227 HsArrAppType -- higher-order (-<<) or first-order (-<)
228 Bool -- True => right-to-left (f -< arg)
229 -- False => left-to-right (arg >- f)
231 | HsArrForm -- Command formation, (| e cmd1 .. cmdn |)
232 (LHsExpr id) -- the operator
233 -- after type-checking, a type abstraction to be
234 -- applied to the type of the local environment tuple
235 (Maybe Fixity) -- fixity (filled in by the renamer), for forms that
236 -- were converted from OpApp's by the renamer
237 [LHsCmdTop id] -- argument commands
240 ---------------------------------------
241 -- Haskell program coverage (Hpc) Support
244 Int -- module-local tick number
245 [id] -- variables in scope
246 (LHsExpr id) -- sub-expression
249 Int -- module-local tick number for True
250 Int -- module-local tick number for False
251 (LHsExpr id) -- sub-expression
253 | HsTickPragma -- A pragma introduced tick
254 (FastString,(Int,Int),(Int,Int)) -- external span for this tick
257 ---------------------------------------
258 -- These constructors only appear temporarily in the parser.
259 -- The renamer translates them into the Right Thing.
261 | EWildPat -- wildcard
263 | EAsPat (Located id) -- as pattern
266 | EViewPat (LHsExpr id) -- view pattern
269 | ELazyPat (LHsExpr id) -- ~ pattern
271 | HsType (LHsType id) -- Explicit type argument; e.g f {| Int |} x y
273 ---------------------------------------
274 -- Finally, HsWrap appears only in typechecker output
276 | HsWrap HsWrapper -- TRANSLATION
279 -- HsTupArg is used for tuple sections
280 -- (,a,) is represented by ExplicitTuple [Mising ty1, Present a, Missing ty3]
281 -- Which in turn stands for (\x:ty1 \y:ty2. (x,a,y))
283 = Present (LHsExpr id) -- The argument
284 | Missing PostTcType -- The argument is missing, but this is its type
286 tupArgPresent :: HsTupArg id -> Bool
287 tupArgPresent (Present {}) = True
288 tupArgPresent (Missing {}) = False
290 type PendingSplice = (Name, LHsExpr Id) -- Typechecked splices, waiting to be
291 -- pasted back in by the desugarer
294 A @Dictionary@, unless of length 0 or 1, becomes a tuple. A
295 @ClassDictLam dictvars methods expr@ is, therefore:
297 \ x -> case x of ( dictvars-and-methods-tuple ) -> expr
301 instance OutputableBndr id => Outputable (HsExpr id) where
302 ppr expr = pprExpr expr
306 -----------------------
307 -- pprExpr, pprLExpr, pprBinds call pprDeeper;
308 -- the underscore versions do not
309 pprLExpr :: OutputableBndr id => LHsExpr id -> SDoc
310 pprLExpr (L _ e) = pprExpr e
312 pprExpr :: OutputableBndr id => HsExpr id -> SDoc
313 pprExpr e | isAtomicHsExpr e || isQuietHsExpr e = ppr_expr e
314 | otherwise = pprDeeper (ppr_expr e)
316 isQuietHsExpr :: HsExpr id -> Bool
317 -- Parentheses do display something, but it gives little info and
318 -- if we go deeper when we go inside them then we get ugly things
320 isQuietHsExpr (HsPar _) = True
321 -- applications don't display anything themselves
322 isQuietHsExpr (HsApp _ _) = True
323 isQuietHsExpr (OpApp _ _ _ _) = True
324 isQuietHsExpr _ = False
326 pprBinds :: (OutputableBndr idL, OutputableBndr idR)
327 => HsLocalBindsLR idL idR -> SDoc
328 pprBinds b = pprDeeper (ppr b)
330 -----------------------
331 ppr_lexpr :: OutputableBndr id => LHsExpr id -> SDoc
332 ppr_lexpr e = ppr_expr (unLoc e)
334 ppr_expr :: OutputableBndr id => HsExpr id -> SDoc
335 ppr_expr (HsVar v) = pprHsVar v
336 ppr_expr (HsIPVar v) = ppr v
337 ppr_expr (HsLit lit) = ppr lit
338 ppr_expr (HsOverLit lit) = ppr lit
339 ppr_expr (HsPar e) = parens (ppr_lexpr e)
341 ppr_expr (HsCoreAnn s e)
342 = vcat [ptext (sLit "HsCoreAnn") <+> ftext s, ppr_lexpr e]
344 ppr_expr (HsApp e1 e2)
345 = let (fun, args) = collect_args e1 [e2] in
346 hang (ppr_lexpr fun) 2 (sep (map pprParendExpr args))
348 collect_args (L _ (HsApp fun arg)) args = collect_args fun (arg:args)
349 collect_args fun args = (fun, args)
351 ppr_expr (OpApp e1 op _ e2)
353 HsVar v -> pp_infixly v
356 pp_e1 = pprDebugParendExpr e1 -- In debug mode, add parens
357 pp_e2 = pprDebugParendExpr e2 -- to make precedence clear
360 = hang (ppr op) 2 (sep [pp_e1, pp_e2])
363 = sep [nest 2 pp_e1, pprHsInfix v, nest 2 pp_e2]
365 ppr_expr (NegApp e _) = char '-' <+> pprDebugParendExpr e
367 ppr_expr (SectionL expr op)
369 HsVar v -> pp_infixly v
372 pp_expr = pprDebugParendExpr expr
374 pp_prefixly = hang (hsep [text " \\ x_ ->", ppr op])
375 4 (hsep [pp_expr, ptext (sLit "x_ )")])
376 pp_infixly v = (sep [pp_expr, pprHsInfix v])
378 ppr_expr (SectionR op expr)
380 HsVar v -> pp_infixly v
383 pp_expr = pprDebugParendExpr expr
385 pp_prefixly = hang (hsep [text "( \\ x_ ->", ppr op, ptext (sLit "x_")])
386 4 ((<>) pp_expr rparen)
388 = (sep [pprHsInfix v, pp_expr])
390 ppr_expr (ExplicitTuple exprs boxity)
391 = tupleParens boxity (fcat (ppr_tup_args exprs))
394 ppr_tup_args (Present e : es) = (ppr_lexpr e <> punc es) : ppr_tup_args es
395 ppr_tup_args (Missing _ : es) = punc es : ppr_tup_args es
397 punc (Present {} : _) = comma <> space
398 punc (Missing {} : _) = comma
401 --avoid using PatternSignatures for stage1 code portability
402 ppr_expr exprType@(HsLam matches)
403 = pprMatches (LambdaExpr `asTypeOf` idType exprType) matches
404 where idType :: HsExpr id -> HsMatchContext id; idType = undefined
406 ppr_expr exprType@(HsCase expr matches)
407 = sep [ sep [ptext (sLit "case"), nest 4 (ppr expr), ptext (sLit "of {")],
408 nest 2 (pprMatches (CaseAlt `asTypeOf` idType exprType) matches <+> char '}') ]
409 where idType :: HsExpr id -> HsMatchContext id; idType = undefined
411 ppr_expr (HsIf e1 e2 e3)
412 = sep [hsep [ptext (sLit "if"), nest 2 (ppr e1), ptext (sLit "then")],
417 -- special case: let ... in let ...
418 ppr_expr (HsLet binds expr@(L _ (HsLet _ _)))
419 = sep [hang (ptext (sLit "let")) 2 (hsep [pprBinds binds, ptext (sLit "in")]),
422 ppr_expr (HsLet binds expr)
423 = sep [hang (ptext (sLit "let")) 2 (pprBinds binds),
424 hang (ptext (sLit "in")) 2 (ppr expr)]
426 ppr_expr (HsDo do_or_list_comp stmts body _) = pprDo do_or_list_comp stmts body
428 ppr_expr (ExplicitList _ exprs)
429 = brackets (pprDeeperList fsep (punctuate comma (map ppr_lexpr exprs)))
431 ppr_expr (ExplicitPArr _ exprs)
432 = pa_brackets (pprDeeperList fsep (punctuate comma (map ppr_lexpr exprs)))
434 ppr_expr (RecordCon con_id _ rbinds)
435 = hang (ppr con_id) 2 (ppr rbinds)
437 ppr_expr (RecordUpd aexp rbinds _ _ _)
438 = hang (pprParendExpr aexp) 2 (ppr rbinds)
440 ppr_expr (ExprWithTySig expr sig)
441 = hang (nest 2 (ppr_lexpr expr) <+> dcolon)
443 ppr_expr (ExprWithTySigOut expr sig)
444 = hang (nest 2 (ppr_lexpr expr) <+> dcolon)
447 ppr_expr (ArithSeq _ info) = brackets (ppr info)
448 ppr_expr (PArrSeq _ info) = pa_brackets (ppr info)
450 ppr_expr EWildPat = char '_'
451 ppr_expr (ELazyPat e) = char '~' <> pprParendExpr e
452 ppr_expr (EAsPat v e) = ppr v <> char '@' <> pprParendExpr e
453 ppr_expr (EViewPat p e) = ppr p <+> ptext (sLit "->") <+> ppr e
455 ppr_expr (HsSCC lbl expr)
456 = sep [ ptext (sLit "_scc_") <+> doubleQuotes (ftext lbl),
459 ppr_expr (HsWrap co_fn e) = pprHsWrapper (pprExpr e) co_fn
460 ppr_expr (HsType id) = ppr id
462 ppr_expr (HsSpliceE s) = pprSplice s
463 ppr_expr (HsBracket b) = pprHsBracket b
464 ppr_expr (HsBracketOut e []) = ppr e
465 ppr_expr (HsBracketOut e ps) = ppr e $$ ptext (sLit "pending") <+> ppr ps
466 ppr_expr (HsQuasiQuoteE qq) = ppr qq
468 ppr_expr (HsProc pat (L _ (HsCmdTop cmd _ _ _)))
469 = hsep [ptext (sLit "proc"), ppr pat, ptext (sLit "->"), ppr cmd]
471 ppr_expr (HsTick tickId vars exp)
472 = pprTicks (ppr exp) $
473 hcat [ptext (sLit "tick<"),
476 hsep (map pprHsVar vars),
479 ppr_expr (HsBinTick tickIdTrue tickIdFalse exp)
480 = pprTicks (ppr exp) $
481 hcat [ptext (sLit "bintick<"),
486 ppr exp,ptext (sLit ")")]
487 ppr_expr (HsTickPragma externalSrcLoc exp)
488 = pprTicks (ppr exp) $
489 hcat [ptext (sLit "tickpragma<"),
495 ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp True)
496 = hsep [ppr_lexpr arrow, ptext (sLit "-<"), ppr_lexpr arg]
497 ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp False)
498 = hsep [ppr_lexpr arg, ptext (sLit ">-"), ppr_lexpr arrow]
499 ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp True)
500 = hsep [ppr_lexpr arrow, ptext (sLit "-<<"), ppr_lexpr arg]
501 ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp False)
502 = hsep [ppr_lexpr arg, ptext (sLit ">>-"), ppr_lexpr arrow]
504 ppr_expr (HsArrForm (L _ (HsVar v)) (Just _) [arg1, arg2])
505 = sep [pprCmdArg (unLoc arg1), hsep [pprHsInfix v, pprCmdArg (unLoc arg2)]]
506 ppr_expr (HsArrForm op _ args)
507 = hang (ptext (sLit "(|") <> ppr_lexpr op)
508 4 (sep (map (pprCmdArg.unLoc) args) <> ptext (sLit "|)"))
510 pprCmdArg :: OutputableBndr id => HsCmdTop id -> SDoc
511 pprCmdArg (HsCmdTop cmd@(L _ (HsArrForm _ Nothing [])) _ _ _)
513 pprCmdArg (HsCmdTop cmd _ _ _)
514 = parens (ppr_lexpr cmd)
516 instance OutputableBndr id => Outputable (HsCmdTop id) where
519 -- add parallel array brackets around a document
521 pa_brackets :: SDoc -> SDoc
522 pa_brackets p = ptext (sLit "[:") <> p <> ptext (sLit ":]")
525 HsSyn records exactly where the user put parens, with HsPar.
526 So generally speaking we print without adding any parens.
527 However, some code is internally generated, and in some places
528 parens are absolutely required; so for these places we use
529 pprParendExpr (but don't print double parens of course).
531 For operator applications we don't add parens, because the oprerator
532 fixities should do the job, except in debug mode (-dppr-debug) so we
533 can see the structure of the parse tree.
536 pprDebugParendExpr :: OutputableBndr id => LHsExpr id -> SDoc
537 pprDebugParendExpr expr
538 = getPprStyle (\sty ->
539 if debugStyle sty then pprParendExpr expr
542 pprParendExpr :: OutputableBndr id => LHsExpr id -> SDoc
545 pp_as_was = pprLExpr expr
546 -- Using pprLExpr makes sure that we go 'deeper'
547 -- I think that is usually (always?) right
550 ArithSeq {} -> pp_as_was
551 PArrSeq {} -> pp_as_was
552 HsLit {} -> pp_as_was
553 HsOverLit {} -> pp_as_was
554 HsVar {} -> pp_as_was
555 HsIPVar {} -> pp_as_was
556 ExplicitTuple {} -> pp_as_was
557 ExplicitList {} -> pp_as_was
558 ExplicitPArr {} -> pp_as_was
559 HsPar {} -> pp_as_was
560 HsBracket {} -> pp_as_was
561 HsBracketOut _ [] -> pp_as_was
563 | isListCompExpr sc -> pp_as_was
564 _ -> parens pp_as_was
566 isAtomicHsExpr :: HsExpr id -> Bool -- A single token
567 isAtomicHsExpr (HsVar {}) = True
568 isAtomicHsExpr (HsLit {}) = True
569 isAtomicHsExpr (HsOverLit {}) = True
570 isAtomicHsExpr (HsIPVar {}) = True
571 isAtomicHsExpr (HsWrap _ e) = isAtomicHsExpr e
572 isAtomicHsExpr (HsPar e) = isAtomicHsExpr (unLoc e)
573 isAtomicHsExpr _ = False
576 %************************************************************************
578 \subsection{Commands (in arrow abstractions)}
580 %************************************************************************
582 We re-use HsExpr to represent these.
585 type HsCmd id = HsExpr id
587 type LHsCmd id = LHsExpr id
589 data HsArrAppType = HsHigherOrderApp | HsFirstOrderApp
592 The legal constructors for commands are:
594 = HsArrApp ... -- as above
596 | HsArrForm ... -- as above
601 | HsLam (Match id) -- kappa
603 -- the renamer turns this one into HsArrForm
604 | OpApp (HsExpr id) -- left operand
605 (HsCmd id) -- operator
606 Fixity -- Renamer adds fixity; bottom until then
607 (HsCmd id) -- right operand
609 | HsPar (HsCmd id) -- parenthesised command
612 [Match id] -- bodies are HsCmd's
615 | HsIf (HsExpr id) -- predicate
616 (HsCmd id) -- then part
617 (HsCmd id) -- else part
620 | HsLet (HsLocalBinds id) -- let(rec)
623 | HsDo (HsStmtContext Name) -- The parameterisation is unimportant
624 -- because in this context we never use
625 -- the PatGuard or ParStmt variant
626 [Stmt id] -- HsExpr's are really HsCmd's
627 PostTcType -- Type of the whole expression
630 Top-level command, introducing a new arrow.
631 This may occur inside a proc (where the stack is empty) or as an
632 argument of a command-forming operator.
635 type LHsCmdTop id = Located (HsCmdTop id)
638 = HsCmdTop (LHsCmd id)
639 [PostTcType] -- types of inputs on the command's stack
640 PostTcType -- return type of the command
641 (SyntaxTable id) -- after type checking:
642 -- names used in the command's desugaring
645 %************************************************************************
647 \subsection{Record binds}
649 %************************************************************************
652 type HsRecordBinds id = HsRecFields id (LHsExpr id)
657 %************************************************************************
659 \subsection{@Match@, @GRHSs@, and @GRHS@ datatypes}
661 %************************************************************************
663 @Match@es are sets of pattern bindings and right hand sides for
664 functions, patterns or case branches. For example, if a function @g@
670 then \tr{g} has two @Match@es: @(x,y) = y@ and @((x:ys),y) = y+1@.
672 It is always the case that each element of an @[Match]@ list has the
673 same number of @pats@s inside it. This corresponds to saying that
674 a function defined by pattern matching must have the same number of
675 patterns in each equation.
680 [LMatch id] -- The alternatives
681 PostTcType -- The type is the type of the entire group
682 -- t1 -> ... -> tn -> tr
683 -- where there are n patterns
685 type LMatch id = Located (Match id)
689 [LPat id] -- The patterns
690 (Maybe (LHsType id)) -- A type signature for the result of the match
691 -- Nothing after typechecking
694 isEmptyMatchGroup :: MatchGroup id -> Bool
695 isEmptyMatchGroup (MatchGroup ms _) = null ms
697 matchGroupArity :: MatchGroup id -> Arity
698 matchGroupArity (MatchGroup [] _)
699 = panic "matchGroupArity" -- Precondition: MatchGroup is non-empty
700 matchGroupArity (MatchGroup (match:matches) _)
701 = ASSERT( all ((== n_pats) . length . hsLMatchPats) matches )
702 -- Assertion just checks that all the matches have the same number of pats
705 n_pats = length (hsLMatchPats match)
707 hsLMatchPats :: LMatch id -> [LPat id]
708 hsLMatchPats (L _ (Match pats _ _)) = pats
710 -- | GRHSs are used both for pattern bindings and for Matches
713 grhssGRHSs :: [LGRHS id], -- ^ Guarded RHSs
714 grhssLocalBinds :: (HsLocalBinds id) -- ^ The where clause
717 type LGRHS id = Located (GRHS id)
719 -- | Guarded Right Hand Side.
720 data GRHS id = GRHS [LStmt id] -- Guards
721 (LHsExpr id) -- Right hand side
724 We know the list must have at least one @Match@ in it.
727 pprMatches :: (OutputableBndr idL, OutputableBndr idR) => HsMatchContext idL -> MatchGroup idR -> SDoc
728 pprMatches ctxt (MatchGroup matches _)
729 = vcat (map (pprMatch ctxt) (map unLoc matches))
730 -- Don't print the type; it's only a place-holder before typechecking
732 -- Exported to HsBinds, which can't see the defn of HsMatchContext
733 pprFunBind :: (OutputableBndr idL, OutputableBndr idR) => idL -> Bool -> MatchGroup idR -> SDoc
734 pprFunBind fun inf matches = pprMatches (FunRhs fun inf) matches
736 -- Exported to HsBinds, which can't see the defn of HsMatchContext
737 pprPatBind :: (OutputableBndr bndr, OutputableBndr id)
738 => LPat bndr -> GRHSs id -> SDoc
739 pprPatBind pat ty@(grhss)
740 = sep [ppr pat, nest 4 (pprGRHSs (PatBindRhs `asTypeOf` idType ty) grhss)]
741 --avoid using PatternSignatures for stage1 code portability
742 where idType :: GRHSs id -> HsMatchContext id; idType = undefined
745 pprMatch :: (OutputableBndr idL, OutputableBndr idR) => HsMatchContext idL -> Match idR -> SDoc
746 pprMatch ctxt (Match pats maybe_ty grhss)
747 = herald <+> sep [sep (map pprParendLPat other_pats),
749 nest 2 (pprGRHSs ctxt grhss)]
754 | not is_infix -> (ppr fun, pats)
756 -- Not pprBndr; the AbsBinds will
757 -- have printed the signature
759 | null pats2 -> (pp_infix, [])
762 | otherwise -> (parens pp_infix, pats2)
765 pp_infix = pprParendLPat pat1 <+> ppr fun <+> pprParendLPat pat2
767 LambdaExpr -> (char '\\', pats)
769 _ -> ASSERT( null pats1 )
770 (ppr pat1, []) -- No parens around the single pat
774 ppr_maybe_ty = case maybe_ty of
775 Just ty -> dcolon <+> ppr ty
779 pprGRHSs :: (OutputableBndr idL, OutputableBndr idR)
780 => HsMatchContext idL -> GRHSs idR -> SDoc
781 pprGRHSs ctxt (GRHSs grhss binds)
782 = vcat (map (pprGRHS ctxt . unLoc) grhss)
783 $$ ppUnless (isEmptyLocalBinds binds)
784 (text "where" $$ nest 4 (pprBinds binds))
786 pprGRHS :: (OutputableBndr idL, OutputableBndr idR)
787 => HsMatchContext idL -> GRHS idR -> SDoc
789 pprGRHS ctxt (GRHS [] expr)
792 pprGRHS ctxt (GRHS guards expr)
793 = sep [char '|' <+> interpp'SP guards, pp_rhs ctxt expr]
795 pp_rhs :: OutputableBndr idR => HsMatchContext idL -> LHsExpr idR -> SDoc
796 pp_rhs ctxt rhs = matchSeparator ctxt <+> pprDeeper (ppr rhs)
799 %************************************************************************
801 \subsection{Do stmts and list comprehensions}
803 %************************************************************************
806 type LStmt id = Located (StmtLR id id)
807 type LStmtLR idL idR = Located (StmtLR idL idR)
809 type Stmt id = StmtLR id id
811 -- The SyntaxExprs in here are used *only* for do-notation, which
812 -- has rebindable syntax. Otherwise they are unused.
814 = BindStmt (LPat idL)
816 (SyntaxExpr idR) -- The (>>=) operator
817 (SyntaxExpr idR) -- The fail operator
818 -- The fail operator is noSyntaxExpr
819 -- if the pattern match can't fail
821 | ExprStmt (LHsExpr idR) -- See Note [ExprStmt]
822 (SyntaxExpr idR) -- The (>>) operator
823 PostTcType -- Element type of the RHS (used for arrows)
825 | LetStmt (HsLocalBindsLR idL idR)
827 -- ParStmts only occur in a list comprehension
828 | ParStmt [([LStmt idL], [idR])]
829 -- After renaming, the ids are the binders bound by the stmts and used
832 -- "qs, then f by e" ==> TransformStmt qs binders f (Just e)
833 -- "qs, then f" ==> TransformStmt qs binders f Nothing
835 [LStmt idL] -- Stmts are the ones to the left of the 'then'
837 [idR] -- After renaming, the IDs are the binders occurring
838 -- within this transform statement that are used after it
840 (LHsExpr idR) -- "then f"
842 (Maybe (LHsExpr idR)) -- "by e" (optional)
845 [LStmt idL] -- Stmts to the *left* of the 'group'
846 -- which generates the tuples to be grouped
848 [(idR, idR)] -- See Note [GroupStmt binder map]
850 (Maybe (LHsExpr idR)) -- "by e" (optional)
853 (LHsExpr idR) -- Left f => explicit "using f"
854 (SyntaxExpr idR)) -- Right f => implicit; filled in with 'groupWith'
857 -- Recursive statement (see Note [How RecStmt works] below)
859 { recS_stmts :: [LStmtLR idL idR]
861 -- The next two fields are only valid after renaming
862 , recS_later_ids :: [idR] -- The ids are a subset of the variables bound by the
863 -- stmts that are used in stmts that follow the RecStmt
865 , recS_rec_ids :: [idR] -- Ditto, but these variables are the "recursive" ones,
866 -- that are used before they are bound in the stmts of
868 -- An Id can be in both groups
869 -- Both sets of Ids are (now) treated monomorphically
870 -- See Note [How RecStmt works] for why they are separate
873 , recS_bind_fn :: SyntaxExpr idR -- The bind function
874 , recS_ret_fn :: SyntaxExpr idR -- The return function
875 , recS_mfix_fn :: SyntaxExpr idR -- The mfix function
877 -- These fields are only valid after typechecking
878 , recS_rec_rets :: [PostTcExpr] -- These expressions correspond 1-to-1 with
879 -- recS_rec_ids, and are the
880 -- expressions that should be returned by
882 -- They may not quite be the Ids themselves,
883 -- because the Id may be *polymorphic*, but
884 -- the returned thing has to be *monomorphic*,
885 -- so they may be type applications
887 , recS_dicts :: DictBinds idR -- Method bindings of Ids bound by the
888 -- RecStmt, and used afterwards
892 Note [GroupStmt binder map]
893 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
894 The [(idR,idR)] in a GroupStmt behaves as follows:
896 * Before renaming: []
899 [ (x27,x27), ..., (z35,z35) ]
900 These are the variables
901 bound by the stmts to the left of the 'group'
902 and used either in the 'by' clause,
903 or in the stmts following the 'group'
904 Each item is a pair of identical variables.
906 * After typechecking:
907 [ (x27:Int, x27:[Int]), ..., (z35:Bool, z35:[Bool]) ]
908 Each pair has the same unique, but different *types*.
912 ExprStmts are a bit tricky, because what they mean
913 depends on the context. Consider the following contexts:
915 A do expression of type (m res_ty)
916 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
917 * ExprStmt E any_ty: do { ....; E; ... }
919 Translation: E >> ...
921 A list comprehensions of type [elt_ty]
922 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
923 * ExprStmt E Bool: [ .. | .... E ]
925 [ .. | .... | ..., E | ... ]
927 Translation: if E then fail else ...
929 A guard list, guarding a RHS of type rhs_ty
930 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
931 * ExprStmt E Bool: f x | ..., E, ... = ...rhs...
933 Translation: if E then fail else ...
935 Array comprehensions are handled like list comprehensions -=chak
937 Note [How RecStmt works]
938 ~~~~~~~~~~~~~~~~~~~~~~~~
942 , RecStmt { recS_rec_ids = [a, c]
943 , recS_stmts = [ BindStmt b (return (a,c))
944 , LetStmt a = ...b...
946 , recS_later_ids = [a, b]
950 Here, the RecStmt binds a,b,c; but
951 - Only a,b are used in the stmts *following* the RecStmt,
952 - Only a,c are used in the stmts *inside* the RecStmt
953 *before* their bindings
955 Why do we need *both* rec_ids and later_ids? For monads they could be
956 combined into a single set of variables, but not for arrows. That
957 follows from the types of the respective feedback operators:
959 mfix :: MonadFix m => (a -> m a) -> m a
960 loop :: ArrowLoop a => a (b,d) (c,d) -> a b c
962 * For mfix, the 'a' covers the union of the later_ids and the rec_ids
963 * For 'loop', 'c' is the later_ids and 'd' is the rec_ids
965 Note [Typing a RecStmt]
966 ~~~~~~~~~~~~~~~~~~~~~~~
967 A (RecStmt stmts) types as if you had written
969 (v1,..,vn, _, ..., _) <- mfix (\~(_, ..., _, r1, ..., rm) ->
971 ; return (v1,..vn, r1, ..., rm) })
973 where v1..vn are the later_ids
974 r1..rm are the rec_ids
978 instance (OutputableBndr idL, OutputableBndr idR) => Outputable (StmtLR idL idR) where
979 ppr stmt = pprStmt stmt
981 pprStmt :: (OutputableBndr idL, OutputableBndr idR) => (StmtLR idL idR) -> SDoc
982 pprStmt (BindStmt pat expr _ _) = hsep [ppr pat, ptext (sLit "<-"), ppr expr]
983 pprStmt (LetStmt binds) = hsep [ptext (sLit "let"), pprBinds binds]
984 pprStmt (ExprStmt expr _ _) = ppr expr
985 pprStmt (ParStmt stmtss) = hsep (map doStmts stmtss)
986 where doStmts stmts = ptext (sLit "| ") <> ppr stmts
988 pprStmt (TransformStmt stmts _ using by)
989 = sep (ppr_lc_stmts stmts ++ [pprTransformStmt using by])
991 pprStmt (GroupStmt stmts _ by using)
992 = sep (ppr_lc_stmts stmts ++ [pprGroupStmt by using])
994 pprStmt (RecStmt { recS_stmts = segment, recS_rec_ids = rec_ids
995 , recS_later_ids = later_ids })
996 = ptext (sLit "rec") <+>
997 vcat [ braces (vcat (map ppr segment))
998 , ifPprDebug (vcat [ ptext (sLit "rec_ids=") <> ppr rec_ids
999 , ptext (sLit "later_ids=") <> ppr later_ids])]
1001 pprTransformStmt :: OutputableBndr id => LHsExpr id -> Maybe (LHsExpr id) -> SDoc
1002 pprTransformStmt using by = sep [ ptext (sLit "then"), nest 2 (ppr using), nest 2 (pprBy by)]
1004 pprGroupStmt :: OutputableBndr id => Maybe (LHsExpr id)
1005 -> Either (LHsExpr id) (SyntaxExpr is)
1007 pprGroupStmt by using
1008 = sep [ ptext (sLit "then group"), nest 2 (pprBy by), nest 2 (ppr_using using)]
1010 ppr_using (Right _) = empty
1011 ppr_using (Left e) = ptext (sLit "using") <+> ppr e
1013 pprBy :: OutputableBndr id => Maybe (LHsExpr id) -> SDoc
1014 pprBy Nothing = empty
1015 pprBy (Just e) = ptext (sLit "by") <+> ppr e
1017 pprDo :: OutputableBndr id => HsStmtContext any -> [LStmt id] -> LHsExpr id -> SDoc
1018 pprDo DoExpr stmts body = ptext (sLit "do") <+> ppr_do_stmts stmts body
1019 pprDo GhciStmt stmts body = ptext (sLit "do") <+> ppr_do_stmts stmts body
1020 pprDo (MDoExpr _) stmts body = ptext (sLit "mdo") <+> ppr_do_stmts stmts body
1021 pprDo ListComp stmts body = brackets $ pprComp stmts body
1022 pprDo PArrComp stmts body = pa_brackets $ pprComp stmts body
1023 pprDo _ _ _ = panic "pprDo" -- PatGuard, ParStmtCxt
1025 ppr_do_stmts :: OutputableBndr id => [LStmt id] -> LHsExpr id -> SDoc
1026 -- Print a bunch of do stmts, with explicit braces and semicolons,
1027 -- so that we are not vulnerable to layout bugs
1028 ppr_do_stmts stmts body
1029 = lbrace <+> pprDeeperList vcat ([ppr s <> semi | s <- stmts] ++ [ppr body])
1032 ppr_lc_stmts :: OutputableBndr id => [LStmt id] -> [SDoc]
1033 ppr_lc_stmts stmts = [ppr s <> comma | s <- stmts]
1035 pprComp :: OutputableBndr id => [LStmt id] -> LHsExpr id -> SDoc
1036 pprComp quals body -- Prints: body | qual1, ..., qualn
1037 = hang (ppr body <+> char '|') 2 (interpp'SP quals)
1040 %************************************************************************
1042 Template Haskell quotation brackets
1044 %************************************************************************
1047 data HsSplice id = HsSplice -- $z or $(f 4)
1048 id -- The id is just a unique name to
1049 (LHsExpr id) -- identify this splice point
1051 instance OutputableBndr id => Outputable (HsSplice id) where
1054 pprSplice :: OutputableBndr id => HsSplice id -> SDoc
1055 pprSplice (HsSplice n e)
1056 = char '$' <> ifPprDebug (brackets (ppr n)) <> pprParendExpr e
1059 data HsBracket id = ExpBr (LHsExpr id) -- [| expr |]
1060 | PatBr (LPat id) -- [p| pat |]
1061 | DecBrL [LHsDecl id] -- [d| decls |]; result of parser
1062 | DecBrG (HsGroup id) -- [d| decls |]; result of renamer
1063 | TypBr (LHsType id) -- [t| type |]
1064 | VarBr id -- 'x, ''T
1066 instance OutputableBndr id => Outputable (HsBracket id) where
1070 pprHsBracket :: OutputableBndr id => HsBracket id -> SDoc
1071 pprHsBracket (ExpBr e) = thBrackets empty (ppr e)
1072 pprHsBracket (PatBr p) = thBrackets (char 'p') (ppr p)
1073 pprHsBracket (DecBrG gp) = thBrackets (char 'd') (ppr gp)
1074 pprHsBracket (DecBrL ds) = thBrackets (char 'd') (vcat (map ppr ds))
1075 pprHsBracket (TypBr t) = thBrackets (char 't') (ppr t)
1076 pprHsBracket (VarBr n) = char '\'' <> ppr n
1077 -- Infelicity: can't show ' vs '', because
1078 -- we can't ask n what its OccName is, because the
1079 -- pretty-printer for HsExpr doesn't ask for NamedThings
1080 -- But the pretty-printer for names will show the OccName class
1082 thBrackets :: SDoc -> SDoc -> SDoc
1083 thBrackets pp_kind pp_body = char '[' <> pp_kind <> char '|' <+>
1084 pp_body <+> ptext (sLit "|]")
1087 %************************************************************************
1089 \subsection{Enumerations and list comprehensions}
1091 %************************************************************************
1094 data ArithSeqInfo id
1096 | FromThen (LHsExpr id)
1098 | FromTo (LHsExpr id)
1100 | FromThenTo (LHsExpr id)
1106 instance OutputableBndr id => Outputable (ArithSeqInfo id) where
1107 ppr (From e1) = hcat [ppr e1, pp_dotdot]
1108 ppr (FromThen e1 e2) = hcat [ppr e1, comma, space, ppr e2, pp_dotdot]
1109 ppr (FromTo e1 e3) = hcat [ppr e1, pp_dotdot, ppr e3]
1110 ppr (FromThenTo e1 e2 e3)
1111 = hcat [ppr e1, comma, space, ppr e2, pp_dotdot, ppr e3]
1114 pp_dotdot = ptext (sLit " .. ")
1118 %************************************************************************
1120 \subsection{HsMatchCtxt}
1122 %************************************************************************
1125 data HsMatchContext id -- Context of a Match
1126 = FunRhs id Bool -- Function binding for f; True <=> written infix
1127 | CaseAlt -- Patterns and guards on a case alternative
1128 | LambdaExpr -- Patterns of a lambda
1129 | ProcExpr -- Patterns of a proc
1130 | PatBindRhs -- Patterns in the *guards* of a pattern binding
1131 | RecUpd -- Record update [used only in DsExpr to
1132 -- tell matchWrapper what sort of
1133 -- runtime error message to generate]
1134 | StmtCtxt (HsStmtContext id) -- Pattern of a do-stmt or list comprehension
1135 | ThPatQuote -- A Template Haskell pattern quotation [p| (a,b) |]
1138 data HsStmtContext id
1141 | GhciStmt -- A command-line Stmt in GHCi pat <- rhs
1142 | MDoExpr PostTcTable -- Recursive do-expression
1143 -- (tiresomely, it needs table
1144 -- of its return/bind ops)
1145 | PArrComp -- Parallel array comprehension
1146 | PatGuard (HsMatchContext id) -- Pattern guard for specified thing
1147 | ParStmtCtxt (HsStmtContext id) -- A branch of a parallel stmt
1148 | TransformStmtCtxt (HsStmtContext id) -- A branch of a transform stmt
1152 isDoExpr :: HsStmtContext id -> Bool
1153 isDoExpr DoExpr = True
1154 isDoExpr (MDoExpr _) = True
1157 isListCompExpr :: HsStmtContext id -> Bool
1158 isListCompExpr ListComp = True
1159 isListCompExpr PArrComp = True
1160 isListCompExpr _ = False
1164 matchSeparator :: HsMatchContext id -> SDoc
1165 matchSeparator (FunRhs {}) = ptext (sLit "=")
1166 matchSeparator CaseAlt = ptext (sLit "->")
1167 matchSeparator LambdaExpr = ptext (sLit "->")
1168 matchSeparator ProcExpr = ptext (sLit "->")
1169 matchSeparator PatBindRhs = ptext (sLit "=")
1170 matchSeparator (StmtCtxt _) = ptext (sLit "<-")
1171 matchSeparator RecUpd = panic "unused"
1172 matchSeparator ThPatQuote = panic "unused"
1176 pprMatchContext :: Outputable id => HsMatchContext id -> SDoc
1177 pprMatchContext (FunRhs fun _) = ptext (sLit "the definition of")
1178 <+> quotes (ppr fun)
1179 pprMatchContext CaseAlt = ptext (sLit "a case alternative")
1180 pprMatchContext RecUpd = ptext (sLit "a record-update construct")
1181 pprMatchContext ThPatQuote = ptext (sLit "a Template Haskell pattern quotation")
1182 pprMatchContext PatBindRhs = ptext (sLit "a pattern binding")
1183 pprMatchContext LambdaExpr = ptext (sLit "a lambda abstraction")
1184 pprMatchContext ProcExpr = ptext (sLit "an arrow abstraction")
1185 pprMatchContext (StmtCtxt ctxt) = ptext (sLit "a pattern binding in")
1186 $$ pprStmtContext ctxt
1188 pprStmtContext :: Outputable id => HsStmtContext id -> SDoc
1189 pprStmtContext (ParStmtCtxt c)
1190 = sep [ptext (sLit "a parallel branch of"), pprStmtContext c]
1191 pprStmtContext (TransformStmtCtxt c)
1192 = sep [ptext (sLit "a transformed branch of"), pprStmtContext c]
1193 pprStmtContext (PatGuard ctxt)
1194 = ptext (sLit "a pattern guard for") $$ pprMatchContext ctxt
1195 pprStmtContext GhciStmt = ptext (sLit "an interactive GHCi command")
1196 pprStmtContext DoExpr = ptext (sLit "a 'do' expression")
1197 pprStmtContext (MDoExpr _) = ptext (sLit "an 'mdo' expression")
1198 pprStmtContext ListComp = ptext (sLit "a list comprehension")
1199 pprStmtContext PArrComp = ptext (sLit "an array comprehension")
1202 pprMatchRhsContext (FunRhs fun) = ptext (sLit "a right-hand side of function") <+> quotes (ppr fun)
1203 pprMatchRhsContext CaseAlt = ptext (sLit "the body of a case alternative")
1204 pprMatchRhsContext PatBindRhs = ptext (sLit "the right-hand side of a pattern binding")
1205 pprMatchRhsContext LambdaExpr = ptext (sLit "the body of a lambda")
1206 pprMatchRhsContext ProcExpr = ptext (sLit "the body of a proc")
1207 pprMatchRhsContext other = panic "pprMatchRhsContext" -- RecUpd, StmtCtxt
1209 -- Used for the result statement of comprehension
1210 -- e.g. the 'e' in [ e | ... ]
1211 -- or the 'r' in f x = r
1212 pprStmtResultContext (PatGuard ctxt) = pprMatchRhsContext ctxt
1213 pprStmtResultContext other = ptext (sLit "the result of") <+> pprStmtContext other
1216 -- Used to generate the string for a *runtime* error message
1217 matchContextErrString :: Outputable id => HsMatchContext id -> SDoc
1218 matchContextErrString (FunRhs fun _) = ptext (sLit "function") <+> ppr fun
1219 matchContextErrString CaseAlt = ptext (sLit "case")
1220 matchContextErrString PatBindRhs = ptext (sLit "pattern binding")
1221 matchContextErrString RecUpd = ptext (sLit "record update")
1222 matchContextErrString LambdaExpr = ptext (sLit "lambda")
1223 matchContextErrString ProcExpr = ptext (sLit "proc")
1224 matchContextErrString ThPatQuote = panic "matchContextErrString" -- Not used at runtime
1225 matchContextErrString (StmtCtxt (ParStmtCtxt c)) = matchContextErrString (StmtCtxt c)
1226 matchContextErrString (StmtCtxt (TransformStmtCtxt c)) = matchContextErrString (StmtCtxt c)
1227 matchContextErrString (StmtCtxt (PatGuard _)) = ptext (sLit "pattern guard")
1228 matchContextErrString (StmtCtxt GhciStmt) = ptext (sLit "interactive GHCi command")
1229 matchContextErrString (StmtCtxt DoExpr) = ptext (sLit "'do' expression")
1230 matchContextErrString (StmtCtxt (MDoExpr _)) = ptext (sLit "'mdo' expression")
1231 matchContextErrString (StmtCtxt ListComp) = ptext (sLit "list comprehension")
1232 matchContextErrString (StmtCtxt PArrComp) = ptext (sLit "array comprehension")
1236 pprMatchInCtxt :: (OutputableBndr idL, OutputableBndr idR)
1237 => HsMatchContext idL -> Match idR -> SDoc
1238 pprMatchInCtxt ctxt match = hang (ptext (sLit "In") <+> pprMatchContext ctxt <> colon)
1239 4 (pprMatch ctxt match)
1241 pprStmtInCtxt :: (OutputableBndr idL, OutputableBndr idR)
1242 => HsStmtContext idL -> StmtLR idL idR -> SDoc
1243 pprStmtInCtxt ctxt stmt = hang (ptext (sLit "In a stmt of") <+> pprStmtContext ctxt <> colon)
1246 -- For Group and Transform Stmts, don't print the nested stmts!
1247 ppr_stmt (GroupStmt _ _ by using) = pprGroupStmt by using
1248 ppr_stmt (TransformStmt _ _ using by) = pprTransformStmt using by
1249 ppr_stmt stmt = pprStmt stmt