2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
6 HsExpr: Abstract Haskell syntax: expressions
11 #include "HsVersions.h"
31 %************************************************************************
33 \subsection{Expressions proper}
35 %************************************************************************
38 type LHsExpr id = Located (HsExpr id)
40 -------------------------
41 -- PostTcExpr is an evidence expression attached to the
42 -- syntax tree by the type checker (c.f. postTcType)
43 -- We use a PostTcTable where there are a bunch of pieces of
44 -- evidence, more than is convenient to keep individually
45 type PostTcExpr = HsExpr Id
46 type PostTcTable = [(Name, Id)]
48 noPostTcExpr :: PostTcExpr
49 noPostTcExpr = HsLit (HsString (fsLit "noPostTcExpr"))
51 noPostTcTable :: PostTcTable
54 -------------------------
55 -- SyntaxExpr is like PostTcExpr, but it's filled in a little earlier,
56 -- by the renamer. It's used for rebindable syntax.
57 -- E.g. (>>=) is filled in before the renamer by the appropriate Name
58 -- for (>>=), and then instantiated by the type checker with its
61 type SyntaxExpr id = HsExpr id
63 noSyntaxExpr :: SyntaxExpr id -- Before renaming, and sometimes after,
64 -- (if the syntax slot makes no sense)
65 noSyntaxExpr = HsLit (HsString (fsLit "noSyntaxExpr"))
68 type SyntaxTable id = [(Name, SyntaxExpr id)]
69 -- *** Currently used only for CmdTop (sigh) ***
70 -- * Before the renamer, this list is noSyntaxTable
72 -- * After the renamer, it takes the form [(std_name, HsVar actual_name)]
73 -- For example, for the 'return' op of a monad
74 -- normal case: (GHC.Base.return, HsVar GHC.Base.return)
75 -- with rebindable syntax: (GHC.Base.return, return_22)
76 -- where return_22 is whatever "return" is in scope
78 -- * After the type checker, it takes the form [(std_name, <expression>)]
79 -- where <expression> is the evidence for the method
81 noSyntaxTable :: SyntaxTable id
85 -------------------------
87 = HsVar id -- variable
88 | HsIPVar (IPName id) -- implicit parameter
89 | HsOverLit (HsOverLit id) -- Overloaded literals
91 | HsLit HsLit -- Simple (non-overloaded) literals
93 | HsLam (MatchGroup id) -- Currently always a single match
95 | HsApp (LHsExpr id) (LHsExpr id) -- Application
97 -- Operator applications:
98 -- NB Bracketed ops such as (+) come out as Vars.
100 -- NB We need an expr for the operator in an OpApp/Section since
101 -- the typechecker may need to apply the operator to a few types.
103 | OpApp (LHsExpr id) -- left operand
104 (LHsExpr id) -- operator
105 Fixity -- Renamer adds fixity; bottom until then
106 (LHsExpr id) -- right operand
108 | NegApp (LHsExpr id) -- negated expr
109 (SyntaxExpr id) -- Name of 'negate'
111 | HsPar (LHsExpr id) -- parenthesised expr
113 | SectionL (LHsExpr id) -- operand
114 (LHsExpr id) -- operator
115 | SectionR (LHsExpr id) -- operator
116 (LHsExpr id) -- operand
118 | HsCase (LHsExpr id)
121 | HsIf (LHsExpr id) -- predicate
122 (LHsExpr id) -- then part
123 (LHsExpr id) -- else part
125 | HsLet (HsLocalBinds id) -- let(rec)
128 | HsDo (HsStmtContext Name) -- The parameterisation is unimportant
129 -- because in this context we never use
130 -- the PatGuard or ParStmt variant
131 [LStmt id] -- "do":one or more stmts
132 (LHsExpr id) -- The body; the last expression in the
133 -- 'do' of [ body | ... ] in a list comp
134 PostTcType -- Type of the whole expression
136 | ExplicitList -- syntactic list
137 PostTcType -- Gives type of components of list
140 | ExplicitPArr -- syntactic parallel array: [:e1, ..., en:]
141 PostTcType -- type of elements of the parallel array
144 | ExplicitTuple -- tuple
146 -- NB: Unit is ExplicitTuple []
147 -- for tuples, we can get the types
148 -- direct from the components
152 -- Record construction
153 | RecordCon (Located id) -- The constructor. After type checking
154 -- it's the dataConWrapId of the constructor
155 PostTcExpr -- Data con Id applied to type args
159 | RecordUpd (LHsExpr id)
161 [DataCon] -- Filled in by the type checker to the
162 -- _non-empty_ list of DataCons that have
163 -- all the upd'd fields
164 [PostTcType] -- Argument types of *input* record type
165 [PostTcType] -- and *output* record type
166 -- For a type family, the arg types are of the *instance* tycon,
167 -- not the family tycon
169 | ExprWithTySig -- e :: type
173 | ExprWithTySigOut -- TRANSLATION
175 (LHsType Name) -- Retain the signature for
176 -- round-tripping purposes
178 | ArithSeq -- arithmetic sequence
182 | PArrSeq -- arith. sequence for parallel array
183 PostTcExpr -- [:e1..e2:] or [:e1, e2..e3:]
186 | HsSCC FastString -- "set cost centre" SCC pragma
187 (LHsExpr id) -- expr whose cost is to be measured
189 | HsCoreAnn FastString -- hdaume: core annotation
192 -----------------------------------------------------------
193 -- MetaHaskell Extensions
195 | HsBracket (HsBracket id)
197 | HsBracketOut (HsBracket Name) -- Output of the type checker is
199 [PendingSplice] -- renamed expression, plus
200 -- _typechecked_ splices to be
201 -- pasted back in by the desugarer
203 | HsSpliceE (HsSplice id)
205 | HsQuasiQuoteE (HsQuasiQuote id)
206 -- See Note [Quasi-quote overview] in TcSplice
208 -----------------------------------------------------------
209 -- Arrow notation extension
211 | HsProc (LPat id) -- arrow abstraction, proc
212 (LHsCmdTop id) -- body of the abstraction
213 -- always has an empty stack
215 ---------------------------------------
216 -- The following are commands, not expressions proper
218 | HsArrApp -- Arrow tail, or arrow application (f -< arg)
219 (LHsExpr id) -- arrow expression, f
220 (LHsExpr id) -- input expression, arg
221 PostTcType -- type of the arrow expressions f,
222 -- of the form a t t', where arg :: t
223 HsArrAppType -- higher-order (-<<) or first-order (-<)
224 Bool -- True => right-to-left (f -< arg)
225 -- False => left-to-right (arg >- f)
227 | HsArrForm -- Command formation, (| e cmd1 .. cmdn |)
228 (LHsExpr id) -- the operator
229 -- after type-checking, a type abstraction to be
230 -- applied to the type of the local environment tuple
231 (Maybe Fixity) -- fixity (filled in by the renamer), for forms that
232 -- were converted from OpApp's by the renamer
233 [LHsCmdTop id] -- argument commands
236 ---------------------------------------
237 -- Haskell program coverage (Hpc) Support
240 Int -- module-local tick number
241 [id] -- variables in scope
242 (LHsExpr id) -- sub-expression
245 Int -- module-local tick number for True
246 Int -- module-local tick number for False
247 (LHsExpr id) -- sub-expression
249 | HsTickPragma -- A pragma introduced tick
250 (FastString,(Int,Int),(Int,Int)) -- external span for this tick
253 ---------------------------------------
254 -- These constructors only appear temporarily in the parser.
255 -- The renamer translates them into the Right Thing.
257 | EWildPat -- wildcard
259 | EAsPat (Located id) -- as pattern
262 | EViewPat (LHsExpr id) -- view pattern
265 | ELazyPat (LHsExpr id) -- ~ pattern
267 | HsType (LHsType id) -- Explicit type argument; e.g f {| Int |} x y
269 ---------------------------------------
270 -- Finally, HsWrap appears only in typechecker output
272 | HsWrap HsWrapper -- TRANSLATION
275 type PendingSplice = (Name, LHsExpr Id) -- Typechecked splices, waiting to be
276 -- pasted back in by the desugarer
279 A @Dictionary@, unless of length 0 or 1, becomes a tuple. A
280 @ClassDictLam dictvars methods expr@ is, therefore:
282 \ x -> case x of ( dictvars-and-methods-tuple ) -> expr
286 instance OutputableBndr id => Outputable (HsExpr id) where
287 ppr expr = pprExpr expr
291 -----------------------
292 -- pprExpr, pprLExpr, pprBinds call pprDeeper;
293 -- the underscore versions do not
294 pprLExpr :: OutputableBndr id => LHsExpr id -> SDoc
295 pprLExpr (L _ e) = pprExpr e
297 pprExpr :: OutputableBndr id => HsExpr id -> SDoc
298 pprExpr e | isAtomicHsExpr e || isQuietHsExpr e = ppr_expr e
299 | otherwise = pprDeeper (ppr_expr e)
301 isQuietHsExpr :: HsExpr id -> Bool
302 -- Parentheses do display something, but it gives little info and
303 -- if we go deeper when we go inside them then we get ugly things
305 isQuietHsExpr (HsPar _) = True
306 -- applications don't display anything themselves
307 isQuietHsExpr (HsApp _ _) = True
308 isQuietHsExpr (OpApp _ _ _ _) = True
309 isQuietHsExpr _ = False
311 pprBinds :: (OutputableBndr idL, OutputableBndr idR)
312 => HsLocalBindsLR idL idR -> SDoc
313 pprBinds b = pprDeeper (ppr b)
315 -----------------------
316 ppr_lexpr :: OutputableBndr id => LHsExpr id -> SDoc
317 ppr_lexpr e = ppr_expr (unLoc e)
319 ppr_expr :: OutputableBndr id => HsExpr id -> SDoc
320 ppr_expr (HsVar v) = pprHsVar v
321 ppr_expr (HsIPVar v) = ppr v
322 ppr_expr (HsLit lit) = ppr lit
323 ppr_expr (HsOverLit lit) = ppr lit
324 ppr_expr (HsPar e) = parens (ppr_lexpr e)
326 ppr_expr (HsCoreAnn s e)
327 = vcat [ptext (sLit "HsCoreAnn") <+> ftext s, ppr_lexpr e]
329 ppr_expr (HsApp e1 e2)
330 = let (fun, args) = collect_args e1 [e2] in
331 hang (ppr_lexpr fun) 2 (sep (map pprParendExpr args))
333 collect_args (L _ (HsApp fun arg)) args = collect_args fun (arg:args)
334 collect_args fun args = (fun, args)
336 ppr_expr (OpApp e1 op _ e2)
338 HsVar v -> pp_infixly v
341 pp_e1 = pprDebugParendExpr e1 -- In debug mode, add parens
342 pp_e2 = pprDebugParendExpr e2 -- to make precedence clear
345 = hang (ppr op) 2 (sep [pp_e1, pp_e2])
348 = sep [nest 2 pp_e1, pprHsInfix v, nest 2 pp_e2]
350 ppr_expr (NegApp e _) = char '-' <+> pprDebugParendExpr e
352 ppr_expr (SectionL expr op)
354 HsVar v -> pp_infixly v
357 pp_expr = pprDebugParendExpr expr
359 pp_prefixly = hang (hsep [text " \\ x_ ->", ppr op])
360 4 (hsep [pp_expr, ptext (sLit "x_ )")])
361 pp_infixly v = (sep [pp_expr, pprHsInfix v])
363 ppr_expr (SectionR op expr)
365 HsVar v -> pp_infixly v
368 pp_expr = pprDebugParendExpr expr
370 pp_prefixly = hang (hsep [text "( \\ x_ ->", ppr op, ptext (sLit "x_")])
371 4 ((<>) pp_expr rparen)
373 = (sep [pprHsInfix v, pp_expr])
375 --avoid using PatternSignatures for stage1 code portability
376 ppr_expr exprType@(HsLam matches)
377 = pprMatches (LambdaExpr `asTypeOf` idType exprType) matches
378 where idType :: HsExpr id -> HsMatchContext id; idType = undefined
380 ppr_expr exprType@(HsCase expr matches)
381 = sep [ sep [ptext (sLit "case"), nest 4 (ppr expr), ptext (sLit "of {")],
382 nest 2 (pprMatches (CaseAlt `asTypeOf` idType exprType) matches <+> char '}') ]
383 where idType :: HsExpr id -> HsMatchContext id; idType = undefined
385 ppr_expr (HsIf e1 e2 e3)
386 = sep [hsep [ptext (sLit "if"), nest 2 (ppr e1), ptext (sLit "then")],
391 -- special case: let ... in let ...
392 ppr_expr (HsLet binds expr@(L _ (HsLet _ _)))
393 = sep [hang (ptext (sLit "let")) 2 (hsep [pprBinds binds, ptext (sLit "in")]),
396 ppr_expr (HsLet binds expr)
397 = sep [hang (ptext (sLit "let")) 2 (pprBinds binds),
398 hang (ptext (sLit "in")) 2 (ppr expr)]
400 ppr_expr (HsDo do_or_list_comp stmts body _) = pprDo do_or_list_comp stmts body
402 ppr_expr (ExplicitList _ exprs)
403 = brackets (pprDeeperList fsep (punctuate comma (map ppr_lexpr exprs)))
405 ppr_expr (ExplicitPArr _ exprs)
406 = pa_brackets (pprDeeperList fsep (punctuate comma (map ppr_lexpr exprs)))
408 ppr_expr (ExplicitTuple exprs boxity)
409 = tupleParens boxity (sep (punctuate comma (map ppr_lexpr exprs)))
411 ppr_expr (RecordCon con_id _ rbinds)
412 = hang (ppr con_id) 2 (ppr rbinds)
414 ppr_expr (RecordUpd aexp rbinds _ _ _)
415 = hang (pprParendExpr aexp) 2 (ppr rbinds)
417 ppr_expr (ExprWithTySig expr sig)
418 = hang (nest 2 (ppr_lexpr expr) <+> dcolon)
420 ppr_expr (ExprWithTySigOut expr sig)
421 = hang (nest 2 (ppr_lexpr expr) <+> dcolon)
424 ppr_expr (ArithSeq _ info) = brackets (ppr info)
425 ppr_expr (PArrSeq _ info) = pa_brackets (ppr info)
427 ppr_expr EWildPat = char '_'
428 ppr_expr (ELazyPat e) = char '~' <> pprParendExpr e
429 ppr_expr (EAsPat v e) = ppr v <> char '@' <> pprParendExpr e
430 ppr_expr (EViewPat p e) = ppr p <+> ptext (sLit "->") <+> ppr e
432 ppr_expr (HsSCC lbl expr)
433 = sep [ ptext (sLit "_scc_") <+> doubleQuotes (ftext lbl),
436 ppr_expr (HsWrap co_fn e) = pprHsWrapper (pprExpr e) co_fn
437 ppr_expr (HsType id) = ppr id
439 ppr_expr (HsSpliceE s) = pprSplice s
440 ppr_expr (HsBracket b) = pprHsBracket b
441 ppr_expr (HsBracketOut e []) = ppr e
442 ppr_expr (HsBracketOut e ps) = ppr e $$ ptext (sLit "pending") <+> ppr ps
443 ppr_expr (HsQuasiQuoteE qq) = ppr qq
445 ppr_expr (HsProc pat (L _ (HsCmdTop cmd _ _ _)))
446 = hsep [ptext (sLit "proc"), ppr pat, ptext (sLit "->"), ppr cmd]
448 ppr_expr (HsTick tickId vars exp)
449 = hcat [ptext (sLit "tick<"),
452 hsep (map pprHsVar vars),
455 ppr_expr (HsBinTick tickIdTrue tickIdFalse exp)
456 = hcat [ptext (sLit "bintick<"),
461 ppr exp,ptext (sLit ")")]
462 ppr_expr (HsTickPragma externalSrcLoc exp)
463 = hcat [ptext (sLit "tickpragma<"),
469 ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp True)
470 = hsep [ppr_lexpr arrow, ptext (sLit "-<"), ppr_lexpr arg]
471 ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp False)
472 = hsep [ppr_lexpr arg, ptext (sLit ">-"), ppr_lexpr arrow]
473 ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp True)
474 = hsep [ppr_lexpr arrow, ptext (sLit "-<<"), ppr_lexpr arg]
475 ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp False)
476 = hsep [ppr_lexpr arg, ptext (sLit ">>-"), ppr_lexpr arrow]
478 ppr_expr (HsArrForm (L _ (HsVar v)) (Just _) [arg1, arg2])
479 = sep [pprCmdArg (unLoc arg1), hsep [pprHsInfix v, pprCmdArg (unLoc arg2)]]
480 ppr_expr (HsArrForm op _ args)
481 = hang (ptext (sLit "(|") <> ppr_lexpr op)
482 4 (sep (map (pprCmdArg.unLoc) args) <> ptext (sLit "|)"))
484 pprCmdArg :: OutputableBndr id => HsCmdTop id -> SDoc
485 pprCmdArg (HsCmdTop cmd@(L _ (HsArrForm _ Nothing [])) _ _ _)
487 pprCmdArg (HsCmdTop cmd _ _ _)
488 = parens (ppr_lexpr cmd)
490 instance OutputableBndr id => Outputable (HsCmdTop id) where
493 -- add parallel array brackets around a document
495 pa_brackets :: SDoc -> SDoc
496 pa_brackets p = ptext (sLit "[:") <> p <> ptext (sLit ":]")
499 HsSyn records exactly where the user put parens, with HsPar.
500 So generally speaking we print without adding any parens.
501 However, some code is internally generated, and in some places
502 parens are absolutely required; so for these places we use
503 pprParendExpr (but don't print double parens of course).
505 For operator applications we don't add parens, because the oprerator
506 fixities should do the job, except in debug mode (-dppr-debug) so we
507 can see the structure of the parse tree.
510 pprDebugParendExpr :: OutputableBndr id => LHsExpr id -> SDoc
511 pprDebugParendExpr expr
512 = getPprStyle (\sty ->
513 if debugStyle sty then pprParendExpr expr
516 pprParendExpr :: OutputableBndr id => LHsExpr id -> SDoc
519 pp_as_was = pprLExpr expr
520 -- Using pprLExpr makes sure that we go 'deeper'
521 -- I think that is usually (always?) right
525 HsOverLit _ -> pp_as_was
527 HsIPVar _ -> pp_as_was
528 ExplicitList _ _ -> pp_as_was
529 ExplicitPArr _ _ -> pp_as_was
530 ExplicitTuple _ _ -> pp_as_was
532 HsBracket _ -> pp_as_was
533 HsBracketOut _ [] -> pp_as_was
535 | isListCompExpr sc -> pp_as_was
536 _ -> parens pp_as_was
538 isAtomicHsExpr :: HsExpr id -> Bool -- A single token
539 isAtomicHsExpr (HsVar {}) = True
540 isAtomicHsExpr (HsLit {}) = True
541 isAtomicHsExpr (HsOverLit {}) = True
542 isAtomicHsExpr (HsIPVar {}) = True
543 isAtomicHsExpr (HsWrap _ e) = isAtomicHsExpr e
544 isAtomicHsExpr (HsPar e) = isAtomicHsExpr (unLoc e)
545 isAtomicHsExpr _ = False
548 %************************************************************************
550 \subsection{Commands (in arrow abstractions)}
552 %************************************************************************
554 We re-use HsExpr to represent these.
557 type HsCmd id = HsExpr id
559 type LHsCmd id = LHsExpr id
561 data HsArrAppType = HsHigherOrderApp | HsFirstOrderApp
564 The legal constructors for commands are:
566 = HsArrApp ... -- as above
568 | HsArrForm ... -- as above
573 | HsLam (Match id) -- kappa
575 -- the renamer turns this one into HsArrForm
576 | OpApp (HsExpr id) -- left operand
577 (HsCmd id) -- operator
578 Fixity -- Renamer adds fixity; bottom until then
579 (HsCmd id) -- right operand
581 | HsPar (HsCmd id) -- parenthesised command
584 [Match id] -- bodies are HsCmd's
587 | HsIf (HsExpr id) -- predicate
588 (HsCmd id) -- then part
589 (HsCmd id) -- else part
592 | HsLet (HsLocalBinds id) -- let(rec)
595 | HsDo (HsStmtContext Name) -- The parameterisation is unimportant
596 -- because in this context we never use
597 -- the PatGuard or ParStmt variant
598 [Stmt id] -- HsExpr's are really HsCmd's
599 PostTcType -- Type of the whole expression
602 Top-level command, introducing a new arrow.
603 This may occur inside a proc (where the stack is empty) or as an
604 argument of a command-forming operator.
607 type LHsCmdTop id = Located (HsCmdTop id)
610 = HsCmdTop (LHsCmd id)
611 [PostTcType] -- types of inputs on the command's stack
612 PostTcType -- return type of the command
613 (SyntaxTable id) -- after type checking:
614 -- names used in the command's desugaring
617 %************************************************************************
619 \subsection{Record binds}
621 %************************************************************************
624 type HsRecordBinds id = HsRecFields id (LHsExpr id)
629 %************************************************************************
631 \subsection{@Match@, @GRHSs@, and @GRHS@ datatypes}
633 %************************************************************************
635 @Match@es are sets of pattern bindings and right hand sides for
636 functions, patterns or case branches. For example, if a function @g@
642 then \tr{g} has two @Match@es: @(x,y) = y@ and @((x:ys),y) = y+1@.
644 It is always the case that each element of an @[Match]@ list has the
645 same number of @pats@s inside it. This corresponds to saying that
646 a function defined by pattern matching must have the same number of
647 patterns in each equation.
652 [LMatch id] -- The alternatives
653 PostTcType -- The type is the type of the entire group
654 -- t1 -> ... -> tn -> tr
655 -- where there are n patterns
657 type LMatch id = Located (Match id)
661 [LPat id] -- The patterns
662 (Maybe (LHsType id)) -- A type signature for the result of the match
663 -- Nothing after typechecking
666 isEmptyMatchGroup :: MatchGroup id -> Bool
667 isEmptyMatchGroup (MatchGroup ms _) = null ms
669 matchGroupArity :: MatchGroup id -> Arity
670 matchGroupArity (MatchGroup [] _)
671 = panic "matchGroupArity" -- Precondition: MatchGroup is non-empty
672 matchGroupArity (MatchGroup (match:matches) _)
673 = ASSERT( all ((== n_pats) . length . hsLMatchPats) matches )
674 -- Assertion just checks that all the matches have the same number of pats
677 n_pats = length (hsLMatchPats match)
679 hsLMatchPats :: LMatch id -> [LPat id]
680 hsLMatchPats (L _ (Match pats _ _)) = pats
682 -- GRHSs are used both for pattern bindings and for Matches
684 = GRHSs [LGRHS id] -- Guarded RHSs
685 (HsLocalBinds id) -- The where clause
687 type LGRHS id = Located (GRHS id)
689 data GRHS id = GRHS [LStmt id] -- Guards
690 (LHsExpr id) -- Right hand side
693 We know the list must have at least one @Match@ in it.
696 pprMatches :: (OutputableBndr idL, OutputableBndr idR) => HsMatchContext idL -> MatchGroup idR -> SDoc
697 pprMatches ctxt (MatchGroup matches _)
698 = vcat (map (pprMatch ctxt) (map unLoc matches))
699 -- Don't print the type; it's only a place-holder before typechecking
701 -- Exported to HsBinds, which can't see the defn of HsMatchContext
702 pprFunBind :: (OutputableBndr idL, OutputableBndr idR) => idL -> Bool -> MatchGroup idR -> SDoc
703 pprFunBind fun inf matches = pprMatches (FunRhs fun inf) matches
705 -- Exported to HsBinds, which can't see the defn of HsMatchContext
706 pprPatBind :: (OutputableBndr bndr, OutputableBndr id)
707 => LPat bndr -> GRHSs id -> SDoc
708 pprPatBind pat ty@(grhss)
709 = sep [ppr pat, nest 4 (pprGRHSs (PatBindRhs `asTypeOf` idType ty) grhss)]
710 --avoid using PatternSignatures for stage1 code portability
711 where idType :: GRHSs id -> HsMatchContext id; idType = undefined
714 pprMatch :: (OutputableBndr idL, OutputableBndr idR) => HsMatchContext idL -> Match idR -> SDoc
715 pprMatch ctxt (Match pats maybe_ty grhss)
716 = herald <+> sep [sep (map ppr other_pats),
718 nest 2 (pprGRHSs ctxt grhss)]
723 | not is_infix -> (ppr fun, pats)
725 -- Not pprBndr; the AbsBinds will
726 -- have printed the signature
728 | null pats3 -> (pp_infix, [])
731 | otherwise -> (parens pp_infix, pats3)
734 (pat1:pat2:pats3) = pats
735 pp_infix = ppr pat1 <+> ppr fun <+> ppr pat2
737 LambdaExpr -> (char '\\', pats)
740 ppr_maybe_ty = case maybe_ty of
741 Just ty -> dcolon <+> ppr ty
745 pprGRHSs :: (OutputableBndr idL, OutputableBndr idR)
746 => HsMatchContext idL -> GRHSs idR -> SDoc
747 pprGRHSs ctxt (GRHSs grhss binds)
748 = vcat (map (pprGRHS ctxt . unLoc) grhss)
749 $$ if isEmptyLocalBinds binds then empty
750 else text "where" $$ nest 4 (pprBinds binds)
752 pprGRHS :: (OutputableBndr idL, OutputableBndr idR)
753 => HsMatchContext idL -> GRHS idR -> SDoc
755 pprGRHS ctxt (GRHS [] expr)
758 pprGRHS ctxt (GRHS guards expr)
759 = sep [char '|' <+> interpp'SP guards, pp_rhs ctxt expr]
761 pp_rhs :: OutputableBndr idR => HsMatchContext idL -> LHsExpr idR -> SDoc
762 pp_rhs ctxt rhs = matchSeparator ctxt <+> pprDeeper (ppr rhs)
765 %************************************************************************
767 \subsection{Do stmts and list comprehensions}
769 %************************************************************************
772 type LStmt id = Located (StmtLR id id)
773 type LStmtLR idL idR = Located (StmtLR idL idR)
775 type Stmt id = StmtLR id id
777 data GroupByClause id
778 = GroupByNothing (LHsExpr id) -- Using expression, i.e.
779 -- "then group using f" ==> GroupByNothing f
780 | GroupBySomething (Either (LHsExpr id) (SyntaxExpr id)) (LHsExpr id)
781 -- "then group using f by e" ==> GroupBySomething (Left f) e
782 -- "then group by e" ==> GroupBySomething (Right _) e: in
783 -- this case the expression is filled
786 -- The SyntaxExprs in here are used *only* for do-notation, which
787 -- has rebindable syntax. Otherwise they are unused.
789 = BindStmt (LPat idL)
791 (SyntaxExpr idR) -- The (>>=) operator
792 (SyntaxExpr idR) -- The fail operator
793 -- The fail operator is noSyntaxExpr
794 -- if the pattern match can't fail
796 | ExprStmt (LHsExpr idR)
797 (SyntaxExpr idR) -- The (>>) operator
798 PostTcType -- Element type of the RHS (used for arrows)
800 | LetStmt (HsLocalBindsLR idL idR)
802 -- ParStmts only occur in a list comprehension
803 | ParStmt [([LStmt idL], [idR])]
804 -- After renaming, the ids are the binders bound by the stmts and used
807 | TransformStmt ([LStmt idL], [idR]) (LHsExpr idR) (Maybe (LHsExpr idR))
808 -- After renaming, the IDs are the binders occurring within this
809 -- transform statement that are used after it
810 -- "qs, then f by e" ==> TransformStmt (qs, binders) f (Just e)
811 -- "qs, then f" ==> TransformStmt (qs, binders) f Nothing
813 | GroupStmt ([LStmt idL], [(idR, idR)]) (GroupByClause idR)
814 -- After renaming, the IDs are the binders occurring within this
815 -- transform statement that are used after it which are paired with
816 -- the names which they group over in statements
818 -- Recursive statement (see Note [RecStmt] below)
819 | RecStmt [LStmtLR idL idR]
820 --- The next two fields are only valid after renaming
821 [idR] -- The ids are a subset of the variables bound by the
822 -- stmts that are used in stmts that follow the RecStmt
824 [idR] -- Ditto, but these variables are the "recursive" ones,
825 -- that are used before they are bound in the stmts of
826 -- the RecStmt. From a type-checking point of view,
827 -- these ones have to be monomorphic
829 --- These fields are only valid after typechecking
830 [PostTcExpr] -- These expressions correspond 1-to-1 with
831 -- the "recursive" [id], and are the
832 -- expressions that should be returned by
834 -- They may not quite be the Ids themselves,
835 -- because the Id may be *polymorphic*, but
836 -- the returned thing has to be *monomorphic*.
837 (DictBinds idR) -- Method bindings of Ids bound by the
838 -- RecStmt, and used afterwards
841 ExprStmts are a bit tricky, because what they mean
842 depends on the context. Consider the following contexts:
844 A do expression of type (m res_ty)
845 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
846 * ExprStmt E any_ty: do { ....; E; ... }
848 Translation: E >> ...
850 A list comprehensions of type [elt_ty]
851 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
852 * ExprStmt E Bool: [ .. | .... E ]
854 [ .. | .... | ..., E | ... ]
856 Translation: if E then fail else ...
858 A guard list, guarding a RHS of type rhs_ty
859 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
860 * ExprStmt E Bool: f x | ..., E, ... = ...rhs...
862 Translation: if E then fail else ...
864 Array comprehensions are handled like list comprehensions -=chak
871 , RecStmt [a::forall a. a -> a, b]
873 [ BindStmt b (return x)
879 Here, the RecStmt binds a,b,c; but
880 - Only a,b are used in the stmts *following* the RecStmt,
881 This 'a' is *polymorphic'
882 - Only a,c are used in the stmts *inside* the RecStmt
883 *before* their bindings
884 This 'a' is monomorphic
886 Nota Bene: the two a's have different types, even though they
891 instance (OutputableBndr idL, OutputableBndr idR) => Outputable (StmtLR idL idR) where
892 ppr stmt = pprStmt stmt
894 pprStmt :: (OutputableBndr idL, OutputableBndr idR) => (StmtLR idL idR) -> SDoc
895 pprStmt (BindStmt pat expr _ _) = hsep [ppr pat, ptext (sLit "<-"), ppr expr]
896 pprStmt (LetStmt binds) = hsep [ptext (sLit "let"), pprBinds binds]
897 pprStmt (ExprStmt expr _ _) = ppr expr
898 pprStmt (ParStmt stmtss) = hsep (map doStmts stmtss)
899 where doStmts stmts = ptext (sLit "| ") <> ppr stmts
900 pprStmt (TransformStmt (stmts, _) usingExpr maybeByExpr)
901 = (hsep [stmtsDoc, ptext (sLit "then"), ppr usingExpr, byExprDoc])
902 where stmtsDoc = interpp'SP stmts
903 byExprDoc = maybe empty (\byExpr -> hsep [ptext (sLit "by"), ppr byExpr]) maybeByExpr
904 pprStmt (GroupStmt (stmts, _) groupByClause) = (hsep [stmtsDoc, ptext (sLit "then group"), pprGroupByClause groupByClause])
905 where stmtsDoc = interpp'SP stmts
906 pprStmt (RecStmt segment _ _ _ _) = ptext (sLit "rec") <+> braces (vcat (map ppr segment))
908 pprGroupByClause :: (OutputableBndr id) => GroupByClause id -> SDoc
909 pprGroupByClause (GroupByNothing usingExpr) = hsep [ptext (sLit "using"), ppr usingExpr]
910 pprGroupByClause (GroupBySomething eitherUsingExpr byExpr) = hsep [ptext (sLit "by"), ppr byExpr, usingExprDoc]
911 where usingExprDoc = either (\usingExpr -> hsep [ptext (sLit "using"), ppr usingExpr]) (const empty) eitherUsingExpr
913 pprDo :: OutputableBndr id => HsStmtContext any -> [LStmt id] -> LHsExpr id -> SDoc
914 pprDo DoExpr stmts body = ptext (sLit "do") <+> pprDeeperList vcat (map ppr stmts ++ [ppr body])
915 pprDo (MDoExpr _) stmts body = ptext (sLit "mdo") <+> pprDeeperList vcat (map ppr stmts ++ [ppr body])
916 pprDo ListComp stmts body = pprComp brackets stmts body
917 pprDo PArrComp stmts body = pprComp pa_brackets stmts body
918 pprDo _ _ _ = panic "pprDo" -- PatGuard, ParStmtCxt
920 pprComp :: OutputableBndr id => (SDoc -> SDoc) -> [LStmt id] -> LHsExpr id -> SDoc
921 pprComp brack quals body
923 hang (ppr body <+> char '|')
927 %************************************************************************
929 Template Haskell quotation brackets
931 %************************************************************************
934 data HsSplice id = HsSplice -- $z or $(f 4)
935 id -- The id is just a unique name to
936 (LHsExpr id) -- identify this splice point
938 instance OutputableBndr id => Outputable (HsSplice id) where
941 pprSplice :: OutputableBndr id => HsSplice id -> SDoc
942 pprSplice (HsSplice n e)
943 = char '$' <> ifPprDebug (brackets (ppr n)) <> pprParendExpr e
946 data HsBracket id = ExpBr (LHsExpr id) -- [| expr |]
947 | PatBr (LPat id) -- [p| pat |]
948 | DecBr (HsGroup id) -- [d| decls |]
949 | TypBr (LHsType id) -- [t| type |]
950 | VarBr id -- 'x, ''T
952 instance OutputableBndr id => Outputable (HsBracket id) where
956 pprHsBracket :: OutputableBndr id => HsBracket id -> SDoc
957 pprHsBracket (ExpBr e) = thBrackets empty (ppr e)
958 pprHsBracket (PatBr p) = thBrackets (char 'p') (ppr p)
959 pprHsBracket (DecBr d) = thBrackets (char 'd') (ppr d)
960 pprHsBracket (TypBr t) = thBrackets (char 't') (ppr t)
961 pprHsBracket (VarBr n) = char '\'' <> ppr n
962 -- Infelicity: can't show ' vs '', because
963 -- we can't ask n what its OccName is, because the
964 -- pretty-printer for HsExpr doesn't ask for NamedThings
965 -- But the pretty-printer for names will show the OccName class
967 thBrackets :: SDoc -> SDoc -> SDoc
968 thBrackets pp_kind pp_body = char '[' <> pp_kind <> char '|' <+>
969 pp_body <+> ptext (sLit "|]")
972 %************************************************************************
974 \subsection{Enumerations and list comprehensions}
976 %************************************************************************
981 | FromThen (LHsExpr id)
983 | FromTo (LHsExpr id)
985 | FromThenTo (LHsExpr id)
991 instance OutputableBndr id => Outputable (ArithSeqInfo id) where
992 ppr (From e1) = hcat [ppr e1, pp_dotdot]
993 ppr (FromThen e1 e2) = hcat [ppr e1, comma, space, ppr e2, pp_dotdot]
994 ppr (FromTo e1 e3) = hcat [ppr e1, pp_dotdot, ppr e3]
995 ppr (FromThenTo e1 e2 e3)
996 = hcat [ppr e1, comma, space, ppr e2, pp_dotdot, ppr e3]
999 pp_dotdot = ptext (sLit " .. ")
1003 %************************************************************************
1005 \subsection{HsMatchCtxt}
1007 %************************************************************************
1010 data HsMatchContext id -- Context of a Match
1011 = FunRhs id Bool -- Function binding for f; True <=> written infix
1012 | CaseAlt -- Guard on a case alternative
1013 | LambdaExpr -- Pattern of a lambda
1014 | ProcExpr -- Pattern of a proc
1015 | PatBindRhs -- Pattern binding
1016 | RecUpd -- Record update [used only in DsExpr to
1017 -- tell matchWrapper what sort of
1018 -- runtime error message to generate]
1019 | StmtCtxt (HsStmtContext id) -- Pattern of a do-stmt or list comprehension
1022 data HsStmtContext id
1025 | MDoExpr PostTcTable -- Recursive do-expression
1026 -- (tiresomely, it needs table
1027 -- of its return/bind ops)
1028 | PArrComp -- Parallel array comprehension
1029 | PatGuard (HsMatchContext id) -- Pattern guard for specified thing
1030 | ParStmtCtxt (HsStmtContext id) -- A branch of a parallel stmt
1031 | TransformStmtCtxt (HsStmtContext id) -- A branch of a transform stmt
1035 isDoExpr :: HsStmtContext id -> Bool
1036 isDoExpr DoExpr = True
1037 isDoExpr (MDoExpr _) = True
1040 isListCompExpr :: HsStmtContext id -> Bool
1041 isListCompExpr ListComp = True
1042 isListCompExpr PArrComp = True
1043 isListCompExpr _ = False
1047 matchSeparator :: HsMatchContext id -> SDoc
1048 matchSeparator (FunRhs {}) = ptext (sLit "=")
1049 matchSeparator CaseAlt = ptext (sLit "->")
1050 matchSeparator LambdaExpr = ptext (sLit "->")
1051 matchSeparator ProcExpr = ptext (sLit "->")
1052 matchSeparator PatBindRhs = ptext (sLit "=")
1053 matchSeparator (StmtCtxt _) = ptext (sLit "<-")
1054 matchSeparator RecUpd = panic "unused"
1058 pprMatchContext :: Outputable id => HsMatchContext id -> SDoc
1059 pprMatchContext (FunRhs fun _) = ptext (sLit "the definition of")
1060 <+> quotes (ppr fun)
1061 pprMatchContext CaseAlt = ptext (sLit "a case alternative")
1062 pprMatchContext RecUpd = ptext (sLit "a record-update construct")
1063 pprMatchContext PatBindRhs = ptext (sLit "a pattern binding")
1064 pprMatchContext LambdaExpr = ptext (sLit "a lambda abstraction")
1065 pprMatchContext ProcExpr = ptext (sLit "an arrow abstraction")
1066 pprMatchContext (StmtCtxt ctxt) = ptext (sLit "a pattern binding in")
1067 $$ pprStmtContext ctxt
1069 pprStmtContext :: Outputable id => HsStmtContext id -> SDoc
1070 pprStmtContext (ParStmtCtxt c)
1071 = sep [ptext (sLit "a parallel branch of"), pprStmtContext c]
1072 pprStmtContext (TransformStmtCtxt c)
1073 = sep [ptext (sLit "a transformed branch of"), pprStmtContext c]
1074 pprStmtContext (PatGuard ctxt)
1075 = ptext (sLit "a pattern guard for") $$ pprMatchContext ctxt
1076 pprStmtContext DoExpr = ptext (sLit "a 'do' expression")
1077 pprStmtContext (MDoExpr _) = ptext (sLit "an 'mdo' expression")
1078 pprStmtContext ListComp = ptext (sLit "a list comprehension")
1079 pprStmtContext PArrComp = ptext (sLit "an array comprehension")
1082 pprMatchRhsContext (FunRhs fun) = ptext (sLit "a right-hand side of function") <+> quotes (ppr fun)
1083 pprMatchRhsContext CaseAlt = ptext (sLit "the body of a case alternative")
1084 pprMatchRhsContext PatBindRhs = ptext (sLit "the right-hand side of a pattern binding")
1085 pprMatchRhsContext LambdaExpr = ptext (sLit "the body of a lambda")
1086 pprMatchRhsContext ProcExpr = ptext (sLit "the body of a proc")
1087 pprMatchRhsContext other = panic "pprMatchRhsContext" -- RecUpd, StmtCtxt
1089 -- Used for the result statement of comprehension
1090 -- e.g. the 'e' in [ e | ... ]
1091 -- or the 'r' in f x = r
1092 pprStmtResultContext (PatGuard ctxt) = pprMatchRhsContext ctxt
1093 pprStmtResultContext other = ptext (sLit "the result of") <+> pprStmtContext other
1096 -- Used to generate the string for a *runtime* error message
1097 matchContextErrString :: Outputable id => HsMatchContext id -> String
1098 matchContextErrString (FunRhs fun _) = "function " ++ showSDoc (ppr fun)
1099 matchContextErrString CaseAlt = "case"
1100 matchContextErrString PatBindRhs = "pattern binding"
1101 matchContextErrString RecUpd = "record update"
1102 matchContextErrString LambdaExpr = "lambda"
1103 matchContextErrString ProcExpr = "proc"
1104 matchContextErrString (StmtCtxt (ParStmtCtxt c)) = matchContextErrString (StmtCtxt c)
1105 matchContextErrString (StmtCtxt (TransformStmtCtxt c)) = matchContextErrString (StmtCtxt c)
1106 matchContextErrString (StmtCtxt (PatGuard _)) = "pattern guard"
1107 matchContextErrString (StmtCtxt DoExpr) = "'do' expression"
1108 matchContextErrString (StmtCtxt (MDoExpr _)) = "'mdo' expression"
1109 matchContextErrString (StmtCtxt ListComp) = "list comprehension"
1110 matchContextErrString (StmtCtxt PArrComp) = "array comprehension"
1114 pprMatchInCtxt :: (OutputableBndr idL, OutputableBndr idR)
1115 => HsMatchContext idL -> Match idR -> SDoc
1116 pprMatchInCtxt ctxt match = hang (ptext (sLit "In") <+> pprMatchContext ctxt <> colon)
1117 4 (pprMatch ctxt match)
1119 pprStmtInCtxt :: (OutputableBndr idL, OutputableBndr idR)
1120 => HsStmtContext idL -> StmtLR idL idR -> SDoc
1121 pprStmtInCtxt ctxt stmt = hang (ptext (sLit "In a stmt of") <+> pprStmtContext ctxt <> colon)