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"
32 %************************************************************************
34 \subsection{Expressions proper}
36 %************************************************************************
39 type LHsExpr id = Located (HsExpr id)
41 -------------------------
42 -- PostTcExpr is an evidence expression attached to the
43 -- syntax tree by the type checker (c.f. postTcType)
44 -- We use a PostTcTable where there are a bunch of pieces of
45 -- evidence, more than is convenient to keep individually
46 type PostTcExpr = HsExpr Id
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.
58 -- E.g. (>>=) is filled in before the renamer by the appropriate Name
59 -- for (>>=), and then instantiated by the type checker with its
62 type SyntaxExpr id = HsExpr id
64 noSyntaxExpr :: SyntaxExpr id -- Before renaming, and sometimes after,
65 -- (if the syntax slot makes no sense)
66 noSyntaxExpr = HsLit (HsString FSLIT("noSyntaxExpr"))
69 type SyntaxTable id = [(Name, SyntaxExpr id)]
70 -- *** Currently used only for CmdTop (sigh) ***
71 -- * Before the renamer, this list is noSyntaxTable
73 -- * After the renamer, it takes the form [(std_name, HsVar actual_name)]
74 -- For example, for the 'return' op of a monad
75 -- normal case: (GHC.Base.return, HsVar GHC.Base.return)
76 -- with rebindable syntax: (GHC.Base.return, return_22)
77 -- where return_22 is whatever "return" is in scope
79 -- * After the type checker, it takes the form [(std_name, <expression>)]
80 -- where <expression> is the evidence for the method
82 noSyntaxTable :: SyntaxTable id
86 -------------------------
88 = HsVar id -- variable
89 | HsIPVar (IPName id) -- implicit parameter
90 | HsOverLit (HsOverLit id) -- Overloaded literals
92 | HsLit HsLit -- Simple (non-overloaded) literals
94 | HsLam (MatchGroup id) -- Currently always a single match
96 | HsApp (LHsExpr id) (LHsExpr id) -- Application
98 -- Operator applications:
99 -- NB Bracketed ops such as (+) come out as Vars.
101 -- NB We need an expr for the operator in an OpApp/Section since
102 -- the typechecker may need to apply the operator to a few types.
104 | OpApp (LHsExpr id) -- left operand
105 (LHsExpr id) -- operator
106 Fixity -- Renamer adds fixity; bottom until then
107 (LHsExpr id) -- right operand
109 | NegApp (LHsExpr id) -- negated expr
110 (SyntaxExpr id) -- Name of 'negate'
112 | HsPar (LHsExpr id) -- parenthesised expr
114 | SectionL (LHsExpr id) -- operand
115 (LHsExpr id) -- operator
116 | SectionR (LHsExpr id) -- operator
117 (LHsExpr id) -- operand
119 | HsCase (LHsExpr id)
122 | HsIf (LHsExpr id) -- predicate
123 (LHsExpr id) -- then part
124 (LHsExpr id) -- else part
126 | HsLet (HsLocalBinds id) -- let(rec)
129 | HsDo (HsStmtContext Name) -- The parameterisation is unimportant
130 -- because in this context we never use
131 -- the PatGuard or ParStmt variant
132 [LStmt id] -- "do":one or more stmts
133 (LHsExpr id) -- The body; the last expression in the
134 -- 'do' of [ body | ... ] in a list comp
135 PostTcType -- Type of the whole expression
137 | ExplicitList -- syntactic list
138 PostTcType -- Gives type of components of list
141 | ExplicitPArr -- syntactic parallel array: [:e1, ..., en:]
142 PostTcType -- type of elements of the parallel array
145 | ExplicitTuple -- tuple
147 -- NB: Unit is ExplicitTuple []
148 -- for tuples, we can get the types
149 -- direct from the components
153 -- Record construction
154 | RecordCon (Located id) -- The constructor. After type checking
155 -- it's the dataConWrapId of the constructor
156 PostTcExpr -- Data con Id applied to type args
160 | RecordUpd (LHsExpr id)
162 [DataCon] -- Filled in by the type checker to the
163 -- *non-empty* list of DataCons that have
164 -- all the upd'd fields
165 [PostTcType] -- Argument types of *input* record type
166 [PostTcType] -- and *output* record type
167 -- For a type family, the arg types are of the *instance* tycon,
168 -- not the family tycon
170 | ExprWithTySig -- e :: type
174 | ExprWithTySigOut -- TRANSLATION
176 (LHsType Name) -- Retain the signature for
177 -- round-tripping purposes
179 | ArithSeq -- arithmetic sequence
183 | PArrSeq -- arith. sequence for parallel array
184 PostTcExpr -- [:e1..e2:] or [:e1, e2..e3:]
187 | HsSCC FastString -- "set cost centre" SCC pragma
188 (LHsExpr id) -- expr whose cost is to be measured
190 | HsCoreAnn FastString -- hdaume: core annotation
193 -----------------------------------------------------------
194 -- MetaHaskell Extensions
196 | HsBracket (HsBracket id)
198 | HsBracketOut (HsBracket Name) -- Output of the type checker is
200 [PendingSplice] -- renamed expression, plus
201 -- *typechecked* splices to be
202 -- pasted back in by the desugarer
204 | HsSpliceE (HsSplice id)
206 -----------------------------------------------------------
207 -- Arrow notation extension
209 | HsProc (LPat id) -- arrow abstraction, proc
210 (LHsCmdTop id) -- body of the abstraction
211 -- always has an empty stack
213 ---------------------------------------
214 -- The following are commands, not expressions proper
216 | HsArrApp -- Arrow tail, or arrow application (f -< arg)
217 (LHsExpr id) -- arrow expression, f
218 (LHsExpr id) -- input expression, arg
219 PostTcType -- type of the arrow expressions f,
220 -- of the form a t t', where arg :: t
221 HsArrAppType -- higher-order (-<<) or first-order (-<)
222 Bool -- True => right-to-left (f -< arg)
223 -- False => left-to-right (arg >- f)
225 | HsArrForm -- Command formation, (| e cmd1 .. cmdn |)
226 (LHsExpr id) -- the operator
227 -- after type-checking, a type abstraction to be
228 -- applied to the type of the local environment tuple
229 (Maybe Fixity) -- fixity (filled in by the renamer), for forms that
230 -- were converted from OpApp's by the renamer
231 [LHsCmdTop id] -- argument commands
234 ---------------------------------------
235 -- Haskell program coverage (Hpc) Support
238 Int -- module-local tick number
239 [id] -- variables in scope
240 (LHsExpr id) -- sub-expression
243 Int -- module-local tick number for True
244 Int -- module-local tick number for False
245 (LHsExpr id) -- sub-expression
247 | HsTickPragma -- A pragma introduced tick
248 (FastString,(Int,Int),(Int,Int)) -- external span for this tick
251 ---------------------------------------
252 -- These constructors only appear temporarily in the parser.
253 -- The renamer translates them into the Right Thing.
255 | EWildPat -- wildcard
257 | EAsPat (Located id) -- as pattern
260 | EViewPat (LHsExpr id) -- view pattern
263 | ELazyPat (LHsExpr id) -- ~ pattern
265 | HsType (LHsType id) -- Explicit type argument; e.g f {| Int |} x y
267 ---------------------------------------
268 -- Finally, HsWrap appears only in typechecker output
270 | HsWrap HsWrapper -- TRANSLATION
273 type PendingSplice = (Name, LHsExpr Id) -- Typechecked splices, waiting to be
274 -- pasted back in by the desugarer
277 A @Dictionary@, unless of length 0 or 1, becomes a tuple. A
278 @ClassDictLam dictvars methods expr@ is, therefore:
280 \ x -> case x of ( dictvars-and-methods-tuple ) -> expr
284 instance OutputableBndr id => Outputable (HsExpr id) where
285 ppr expr = pprExpr expr
289 -----------------------
290 -- pprExpr, pprLExpr, pprBinds call pprDeeper;
291 -- the underscore versions do not
292 pprLExpr :: OutputableBndr id => LHsExpr id -> SDoc
293 pprLExpr (L _ e) = pprExpr e
295 pprExpr :: OutputableBndr id => HsExpr id -> SDoc
296 pprExpr e | isAtomicHsExpr e || isQuietHsExpr e = ppr_expr e
297 | otherwise = pprDeeper (ppr_expr e)
299 isQuietHsExpr :: HsExpr id -> Bool
300 -- Parentheses do display something, but it gives little info and
301 -- if we go deeper when we go inside them then we get ugly things
303 isQuietHsExpr (HsPar _) = True
304 -- applications don't display anything themselves
305 isQuietHsExpr (HsApp _ _) = True
306 isQuietHsExpr (OpApp _ _ _ _) = True
307 isQuietHsExpr _ = False
309 pprBinds :: (OutputableBndr idL, OutputableBndr idR)
310 => HsLocalBindsLR idL idR -> SDoc
311 pprBinds b = pprDeeper (ppr b)
313 -----------------------
314 ppr_lexpr :: OutputableBndr id => LHsExpr id -> SDoc
315 ppr_lexpr e = ppr_expr (unLoc e)
317 ppr_expr :: OutputableBndr id => HsExpr id -> SDoc
318 ppr_expr (HsVar v) = pprHsVar v
319 ppr_expr (HsIPVar v) = ppr v
320 ppr_expr (HsLit lit) = ppr lit
321 ppr_expr (HsOverLit lit) = ppr lit
322 ppr_expr (HsPar e) = parens (ppr_lexpr e)
324 ppr_expr (HsCoreAnn s e)
325 = vcat [ptext SLIT("HsCoreAnn") <+> ftext s, ppr_lexpr e]
327 ppr_expr (HsApp e1 e2)
328 = let (fun, args) = collect_args e1 [e2] in
329 hang (ppr_lexpr fun) 2 (sep (map pprParendExpr args))
331 collect_args (L _ (HsApp fun arg)) args = collect_args fun (arg:args)
332 collect_args fun args = (fun, args)
334 ppr_expr (OpApp e1 op _ e2)
336 HsVar v -> pp_infixly v
339 pp_e1 = pprDebugParendExpr e1 -- In debug mode, add parens
340 pp_e2 = pprDebugParendExpr e2 -- to make precedence clear
343 = hang (ppr op) 2 (sep [pp_e1, pp_e2])
346 = sep [nest 2 pp_e1, pprInfix v, nest 2 pp_e2]
348 ppr_expr (NegApp e _) = char '-' <+> pprDebugParendExpr e
350 ppr_expr (SectionL expr op)
352 HsVar v -> pp_infixly v
355 pp_expr = pprDebugParendExpr expr
357 pp_prefixly = hang (hsep [text " \\ x_ ->", ppr op])
358 4 (hsep [pp_expr, ptext SLIT("x_ )")])
359 pp_infixly v = (sep [pp_expr, pprInfix v])
361 ppr_expr (SectionR op expr)
363 HsVar v -> pp_infixly v
366 pp_expr = pprDebugParendExpr expr
368 pp_prefixly = hang (hsep [text "( \\ x_ ->", ppr op, ptext SLIT("x_")])
369 4 ((<>) pp_expr rparen)
371 = (sep [pprInfix v, pp_expr])
373 ppr_expr (HsLam matches :: HsExpr id)
374 = pprMatches (LambdaExpr :: HsMatchContext id) matches
376 ppr_expr (HsCase expr matches :: HsExpr id)
377 = sep [ sep [ptext SLIT("case"), nest 4 (ppr expr), ptext SLIT("of")],
378 nest 2 (pprMatches (CaseAlt :: HsMatchContext id) matches) ]
380 ppr_expr (HsIf e1 e2 e3)
381 = sep [hsep [ptext SLIT("if"), nest 2 (ppr e1), ptext SLIT("then")],
386 -- special case: let ... in let ...
387 ppr_expr (HsLet binds expr@(L _ (HsLet _ _)))
388 = sep [hang (ptext SLIT("let")) 2 (hsep [pprBinds binds, ptext SLIT("in")]),
391 ppr_expr (HsLet binds expr)
392 = sep [hang (ptext SLIT("let")) 2 (pprBinds binds),
393 hang (ptext SLIT("in")) 2 (ppr expr)]
395 ppr_expr (HsDo do_or_list_comp stmts body _) = pprDo do_or_list_comp stmts body
397 ppr_expr (ExplicitList _ exprs)
398 = brackets (pprDeeperList fsep (punctuate comma (map ppr_lexpr exprs)))
400 ppr_expr (ExplicitPArr _ exprs)
401 = pa_brackets (pprDeeperList fsep (punctuate comma (map ppr_lexpr exprs)))
403 ppr_expr (ExplicitTuple exprs boxity)
404 = tupleParens boxity (sep (punctuate comma (map ppr_lexpr exprs)))
406 ppr_expr (RecordCon con_id _ rbinds)
407 = hang (ppr con_id) 2 (ppr rbinds)
409 ppr_expr (RecordUpd aexp rbinds _ _ _)
410 = hang (pprParendExpr aexp) 2 (ppr rbinds)
412 ppr_expr (ExprWithTySig expr sig)
413 = hang (nest 2 (ppr_lexpr expr) <+> dcolon)
415 ppr_expr (ExprWithTySigOut expr sig)
416 = hang (nest 2 (ppr_lexpr expr) <+> dcolon)
419 ppr_expr (ArithSeq _ info) = brackets (ppr info)
420 ppr_expr (PArrSeq _ info) = pa_brackets (ppr info)
422 ppr_expr EWildPat = char '_'
423 ppr_expr (ELazyPat e) = char '~' <> pprParendExpr e
424 ppr_expr (EAsPat v e) = ppr v <> char '@' <> pprParendExpr e
425 ppr_expr (EViewPat p e) = ppr p <+> ptext SLIT("->") <+> ppr e
427 ppr_expr (HsSCC lbl expr)
428 = sep [ ptext SLIT("_scc_") <+> doubleQuotes (ftext lbl),
431 ppr_expr (HsWrap co_fn e) = pprHsWrapper (pprExpr e) co_fn
432 ppr_expr (HsType id) = ppr id
434 ppr_expr (HsSpliceE s) = pprSplice s
435 ppr_expr (HsBracket b) = pprHsBracket b
436 ppr_expr (HsBracketOut e []) = ppr e
437 ppr_expr (HsBracketOut e ps) = ppr e $$ ptext SLIT("pending") <+> ppr ps
439 ppr_expr (HsProc pat (L _ (HsCmdTop cmd _ _ _)))
440 = hsep [ptext SLIT("proc"), ppr pat, ptext SLIT("->"), ppr cmd]
442 ppr_expr (HsTick tickId vars exp)
443 = hcat [ptext SLIT("tick<"),
446 hsep (map pprHsVar vars),
449 ppr_expr (HsBinTick tickIdTrue tickIdFalse exp)
450 = hcat [ptext SLIT("bintick<"),
455 ppr exp,ptext SLIT(")")]
456 ppr_expr (HsTickPragma externalSrcLoc exp)
457 = hcat [ptext SLIT("tickpragma<"),
463 ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp True)
464 = hsep [ppr_lexpr arrow, ptext SLIT("-<"), ppr_lexpr arg]
465 ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp False)
466 = hsep [ppr_lexpr arg, ptext SLIT(">-"), ppr_lexpr arrow]
467 ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp True)
468 = hsep [ppr_lexpr arrow, ptext SLIT("-<<"), ppr_lexpr arg]
469 ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp False)
470 = hsep [ppr_lexpr arg, ptext SLIT(">>-"), ppr_lexpr arrow]
472 ppr_expr (HsArrForm (L _ (HsVar v)) (Just _) [arg1, arg2])
473 = sep [pprCmdArg (unLoc arg1), hsep [pprInfix v, pprCmdArg (unLoc arg2)]]
474 ppr_expr (HsArrForm op _ args)
475 = hang (ptext SLIT("(|") <> ppr_lexpr op)
476 4 (sep (map (pprCmdArg.unLoc) args) <> ptext SLIT("|)"))
478 pprCmdArg :: OutputableBndr id => HsCmdTop id -> SDoc
479 pprCmdArg (HsCmdTop cmd@(L _ (HsArrForm _ Nothing [])) _ _ _)
481 pprCmdArg (HsCmdTop cmd _ _ _)
482 = parens (ppr_lexpr cmd)
484 -- Put a var in backquotes if it's not an operator already
485 pprInfix :: Outputable name => name -> SDoc
486 pprInfix v | isOperator ppr_v = ppr_v
487 | otherwise = char '`' <> ppr_v <> char '`'
490 -- add parallel array brackets around a document
492 pa_brackets :: SDoc -> SDoc
493 pa_brackets p = ptext SLIT("[:") <> p <> ptext SLIT(":]")
496 HsSyn records exactly where the user put parens, with HsPar.
497 So generally speaking we print without adding any parens.
498 However, some code is internally generated, and in some places
499 parens are absolutely required; so for these places we use
500 pprParendExpr (but don't print double parens of course).
502 For operator applications we don't add parens, because the oprerator
503 fixities should do the job, except in debug mode (-dppr-debug) so we
504 can see the structure of the parse tree.
507 pprDebugParendExpr :: OutputableBndr id => LHsExpr id -> SDoc
508 pprDebugParendExpr expr
509 = getPprStyle (\sty ->
510 if debugStyle sty then pprParendExpr expr
513 pprParendExpr :: OutputableBndr id => LHsExpr id -> SDoc
516 pp_as_was = pprLExpr expr
517 -- Using pprLExpr makes sure that we go 'deeper'
518 -- I think that is usually (always?) right
522 HsOverLit _ -> pp_as_was
524 HsIPVar _ -> pp_as_was
525 ExplicitList _ _ -> pp_as_was
526 ExplicitPArr _ _ -> pp_as_was
527 ExplicitTuple _ _ -> pp_as_was
529 HsBracket _ -> pp_as_was
530 HsBracketOut _ [] -> pp_as_was
532 | isListCompExpr sc -> pp_as_was
533 _ -> parens pp_as_was
535 isAtomicHsExpr :: HsExpr id -> Bool -- A single token
536 isAtomicHsExpr (HsVar {}) = True
537 isAtomicHsExpr (HsLit {}) = True
538 isAtomicHsExpr (HsOverLit {}) = True
539 isAtomicHsExpr (HsIPVar {}) = True
540 isAtomicHsExpr (HsWrap _ e) = isAtomicHsExpr e
541 isAtomicHsExpr (HsPar e) = isAtomicHsExpr (unLoc e)
542 isAtomicHsExpr _ = False
545 %************************************************************************
547 \subsection{Commands (in arrow abstractions)}
549 %************************************************************************
551 We re-use HsExpr to represent these.
554 type HsCmd id = HsExpr id
556 type LHsCmd id = LHsExpr id
558 data HsArrAppType = HsHigherOrderApp | HsFirstOrderApp
561 The legal constructors for commands are:
563 = HsArrApp ... -- as above
565 | HsArrForm ... -- as above
570 | HsLam (Match id) -- kappa
572 -- the renamer turns this one into HsArrForm
573 | OpApp (HsExpr id) -- left operand
574 (HsCmd id) -- operator
575 Fixity -- Renamer adds fixity; bottom until then
576 (HsCmd id) -- right operand
578 | HsPar (HsCmd id) -- parenthesised command
581 [Match id] -- bodies are HsCmd's
584 | HsIf (HsExpr id) -- predicate
585 (HsCmd id) -- then part
586 (HsCmd id) -- else part
589 | HsLet (HsLocalBinds id) -- let(rec)
592 | HsDo (HsStmtContext Name) -- The parameterisation is unimportant
593 -- because in this context we never use
594 -- the PatGuard or ParStmt variant
595 [Stmt id] -- HsExpr's are really HsCmd's
596 PostTcType -- Type of the whole expression
599 Top-level command, introducing a new arrow.
600 This may occur inside a proc (where the stack is empty) or as an
601 argument of a command-forming operator.
604 type LHsCmdTop id = Located (HsCmdTop id)
607 = HsCmdTop (LHsCmd id)
608 [PostTcType] -- types of inputs on the command's stack
609 PostTcType -- return type of the command
610 (SyntaxTable id) -- after type checking:
611 -- names used in the command's desugaring
614 %************************************************************************
616 \subsection{Record binds}
618 %************************************************************************
621 type HsRecordBinds id = HsRecFields id (LHsExpr id)
626 %************************************************************************
628 \subsection{@Match@, @GRHSs@, and @GRHS@ datatypes}
630 %************************************************************************
632 @Match@es are sets of pattern bindings and right hand sides for
633 functions, patterns or case branches. For example, if a function @g@
639 then \tr{g} has two @Match@es: @(x,y) = y@ and @((x:ys),y) = y+1@.
641 It is always the case that each element of an @[Match]@ list has the
642 same number of @pats@s inside it. This corresponds to saying that
643 a function defined by pattern matching must have the same number of
644 patterns in each equation.
649 [LMatch id] -- The alternatives
650 PostTcType -- The type is the type of the entire group
651 -- t1 -> ... -> tn -> tr
652 -- where there are n patterns
654 type LMatch id = Located (Match id)
658 [LPat id] -- The patterns
659 (Maybe (LHsType id)) -- A type signature for the result of the match
660 -- Nothing after typechecking
663 matchGroupArity :: MatchGroup id -> Arity
664 matchGroupArity (MatchGroup [] _)
665 = panic "matchGroupArity" -- MatchGroup is never empty
666 matchGroupArity (MatchGroup (match:matches) _)
667 = ASSERT( all ((== n_pats) . length . hsLMatchPats) matches )
668 -- Assertion just checks that all the matches have the same number of pats
671 n_pats = length (hsLMatchPats match)
673 hsLMatchPats :: LMatch id -> [LPat id]
674 hsLMatchPats (L _ (Match pats _ _)) = pats
676 -- GRHSs are used both for pattern bindings and for Matches
678 = GRHSs [LGRHS id] -- Guarded RHSs
679 (HsLocalBinds id) -- The where clause
681 type LGRHS id = Located (GRHS id)
683 data GRHS id = GRHS [LStmt id] -- Guards
684 (LHsExpr id) -- Right hand side
687 We know the list must have at least one @Match@ in it.
690 pprMatches :: (OutputableBndr idL, OutputableBndr idR) => HsMatchContext idL -> MatchGroup idR -> SDoc
691 pprMatches ctxt (MatchGroup matches _)
692 = vcat (map (pprMatch ctxt) (map unLoc matches))
693 -- Don't print the type; it's only a place-holder before typechecking
695 -- Exported to HsBinds, which can't see the defn of HsMatchContext
696 pprFunBind :: (OutputableBndr idL, OutputableBndr idR) => idL -> Bool -> MatchGroup idR -> SDoc
697 pprFunBind fun inf matches = pprMatches (FunRhs fun inf) matches
699 -- Exported to HsBinds, which can't see the defn of HsMatchContext
700 pprPatBind :: (OutputableBndr bndr, OutputableBndr id)
701 => LPat bndr -> GRHSs id -> SDoc
702 pprPatBind pat (grhss :: GRHSs id)
703 = sep [ppr pat, nest 4 (pprGRHSs (PatBindRhs :: HsMatchContext id) grhss)]
706 pprMatch :: (OutputableBndr idL, OutputableBndr idR) => HsMatchContext idL -> Match idR -> SDoc
707 pprMatch ctxt (Match pats maybe_ty grhss)
708 = herald <+> sep [sep (map ppr other_pats),
710 nest 2 (pprGRHSs ctxt grhss)]
715 | not is_infix -> (ppr fun, pats)
717 -- Not pprBndr; the AbsBinds will
718 -- have printed the signature
720 | null pats3 -> (pp_infix, [])
723 | otherwise -> (parens pp_infix, pats3)
726 (pat1:pat2:pats3) = pats
727 pp_infix = ppr pat1 <+> ppr fun <+> ppr pat2
729 LambdaExpr -> (char '\\', pats)
732 ppr_maybe_ty = case maybe_ty of
733 Just ty -> dcolon <+> ppr ty
737 pprGRHSs :: (OutputableBndr idL, OutputableBndr idR)
738 => HsMatchContext idL -> GRHSs idR -> SDoc
739 pprGRHSs ctxt (GRHSs grhss binds)
740 = vcat (map (pprGRHS ctxt . unLoc) grhss)
741 $$ if isEmptyLocalBinds binds then empty
742 else text "where" $$ nest 4 (pprBinds binds)
744 pprGRHS :: (OutputableBndr idL, OutputableBndr idR)
745 => HsMatchContext idL -> GRHS idR -> SDoc
747 pprGRHS ctxt (GRHS [] expr)
750 pprGRHS ctxt (GRHS guards expr)
751 = sep [char '|' <+> interpp'SP guards, pp_rhs ctxt expr]
753 pp_rhs :: OutputableBndr idR => HsMatchContext idL -> LHsExpr idR -> SDoc
754 pp_rhs ctxt rhs = matchSeparator ctxt <+> pprDeeper (ppr rhs)
757 %************************************************************************
759 \subsection{Do stmts and list comprehensions}
761 %************************************************************************
764 type LStmt id = Located (StmtLR id id)
765 type LStmtLR idL idR = Located (StmtLR idL idR)
767 type Stmt id = StmtLR id id
769 data GroupByClause id
770 = GroupByNothing (LHsExpr id) -- Using expression, i.e.
771 -- "then group using f" ==> GroupByNothing f
772 | GroupBySomething (Either (LHsExpr id) (SyntaxExpr id)) (LHsExpr id)
773 -- "then group using f by e" ==> GroupBySomething (Left f) e
774 -- "then group by e" ==> GroupBySomething (Right _) e: in
775 -- this case the expression is filled
778 -- The SyntaxExprs in here are used *only* for do-notation, which
779 -- has rebindable syntax. Otherwise they are unused.
781 = BindStmt (LPat idL)
783 (SyntaxExpr idR) -- The (>>=) operator
784 (SyntaxExpr idR) -- The fail operator
785 -- The fail operator is noSyntaxExpr
786 -- if the pattern match can't fail
788 | ExprStmt (LHsExpr idR)
789 (SyntaxExpr idR) -- The (>>) operator
790 PostTcType -- Element type of the RHS (used for arrows)
792 | LetStmt (HsLocalBindsLR idL idR)
794 -- ParStmts only occur in a list comprehension
795 | ParStmt [([LStmt idL], [idR])]
796 -- After renaming, the ids are the binders bound by the stmts and used
799 | TransformStmt ([LStmt idL], [idR]) (LHsExpr idR) (Maybe (LHsExpr idR))
800 -- After renaming, the IDs are the binders occurring within this
801 -- transform statement that are used after it
802 -- "qs, then f by e" ==> TransformStmt (qs, binders) f (Just e)
803 -- "qs, then f" ==> TransformStmt (qs, binders) f Nothing
805 | GroupStmt ([LStmt idL], [(idR, idR)]) (GroupByClause idR)
806 -- After renaming, the IDs are the binders occurring within this
807 -- transform statement that are used after it which are paired with
808 -- the names which they group over in statements
810 -- Recursive statement (see Note [RecStmt] below)
811 | RecStmt [LStmtLR idL idR]
812 --- The next two fields are only valid after renaming
813 [idR] -- The ids are a subset of the variables bound by the
814 -- stmts that are used in stmts that follow the RecStmt
816 [idR] -- Ditto, but these variables are the "recursive" ones,
817 -- that are used before they are bound in the stmts of
818 -- the RecStmt. From a type-checking point of view,
819 -- these ones have to be monomorphic
821 --- These fields are only valid after typechecking
822 [PostTcExpr] -- These expressions correspond 1-to-1 with
823 -- the "recursive" [id], and are the
824 -- expressions that should be returned by
826 -- They may not quite be the Ids themselves,
827 -- because the Id may be *polymorphic*, but
828 -- the returned thing has to be *monomorphic*.
829 (DictBinds idR) -- Method bindings of Ids bound by the
830 -- RecStmt, and used afterwards
833 ExprStmts are a bit tricky, because what they mean
834 depends on the context. Consider the following contexts:
836 A do expression of type (m res_ty)
837 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
838 * ExprStmt E any_ty: do { ....; E; ... }
840 Translation: E >> ...
842 A list comprehensions of type [elt_ty]
843 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
844 * ExprStmt E Bool: [ .. | .... E ]
846 [ .. | .... | ..., E | ... ]
848 Translation: if E then fail else ...
850 A guard list, guarding a RHS of type rhs_ty
851 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
852 * ExprStmt E Bool: f x | ..., E, ... = ...rhs...
854 Translation: if E then fail else ...
856 Array comprehensions are handled like list comprehensions -=chak
863 , RecStmt [a::forall a. a -> a, b]
865 [ BindStmt b (return x)
871 Here, the RecStmt binds a,b,c; but
872 - Only a,b are used in the stmts *following* the RecStmt,
873 This 'a' is *polymorphic'
874 - Only a,c are used in the stmts *inside* the RecStmt
875 *before* their bindings
876 This 'a' is monomorphic
878 Nota Bene: the two a's have different types, even though they
883 instance (OutputableBndr idL, OutputableBndr idR) => Outputable (StmtLR idL idR) where
884 ppr stmt = pprStmt stmt
886 pprStmt :: (OutputableBndr idL, OutputableBndr idR) => (StmtLR idL idR) -> SDoc
887 pprStmt (BindStmt pat expr _ _) = hsep [ppr pat, ptext SLIT("<-"), ppr expr]
888 pprStmt (LetStmt binds) = hsep [ptext SLIT("let"), pprBinds binds]
889 pprStmt (ExprStmt expr _ _) = ppr expr
890 pprStmt (ParStmt stmtss) = hsep (map doStmts stmtss)
891 where doStmts stmts = ptext SLIT("| ") <> ppr stmts
892 pprStmt (TransformStmt (stmts, _) usingExpr maybeByExpr)
893 = (hsep [stmtsDoc, ptext SLIT("then"), ppr usingExpr, byExprDoc])
894 where stmtsDoc = interpp'SP stmts
895 byExprDoc = maybe empty (\byExpr -> hsep [ptext SLIT("by"), ppr byExpr]) maybeByExpr
896 pprStmt (GroupStmt (stmts, _) groupByClause) = (hsep [stmtsDoc, ptext SLIT("then group"), pprGroupByClause groupByClause])
897 where stmtsDoc = interpp'SP stmts
898 pprStmt (RecStmt segment _ _ _ _) = ptext SLIT("rec") <+> braces (vcat (map ppr segment))
900 pprGroupByClause :: (OutputableBndr id) => GroupByClause id -> SDoc
901 pprGroupByClause (GroupByNothing usingExpr) = hsep [ptext SLIT("using"), ppr usingExpr]
902 pprGroupByClause (GroupBySomething eitherUsingExpr byExpr) = hsep [ptext SLIT("by"), ppr byExpr, usingExprDoc]
903 where usingExprDoc = either (\usingExpr -> hsep [ptext SLIT("using"), ppr usingExpr]) (const empty) eitherUsingExpr
905 pprDo :: OutputableBndr id => HsStmtContext any -> [LStmt id] -> LHsExpr id -> SDoc
906 pprDo DoExpr stmts body = ptext SLIT("do") <+> pprDeeperList vcat (map ppr stmts ++ [ppr body])
907 pprDo (MDoExpr _) stmts body = ptext SLIT("mdo") <+> pprDeeperList vcat (map ppr stmts ++ [ppr body])
908 pprDo ListComp stmts body = pprComp brackets stmts body
909 pprDo PArrComp stmts body = pprComp pa_brackets stmts body
910 pprDo _ _ _ = panic "pprDo" -- PatGuard, ParStmtCxt
912 pprComp :: OutputableBndr id => (SDoc -> SDoc) -> [LStmt id] -> LHsExpr id -> SDoc
913 pprComp brack quals body
915 hang (ppr body <+> char '|')
919 %************************************************************************
921 Template Haskell quotation brackets
923 %************************************************************************
926 data HsSplice id = HsSplice -- $z or $(f 4)
927 id -- The id is just a unique name to
928 (LHsExpr id) -- identify this splice point
930 instance OutputableBndr id => Outputable (HsSplice id) where
933 pprSplice :: OutputableBndr id => HsSplice id -> SDoc
934 pprSplice (HsSplice n e)
935 = char '$' <> ifPprDebug (brackets (ppr n)) <> pprParendExpr e
938 data HsBracket id = ExpBr (LHsExpr id) -- [| expr |]
939 | PatBr (LPat id) -- [p| pat |]
940 | DecBr (HsGroup id) -- [d| decls |]
941 | TypBr (LHsType id) -- [t| type |]
942 | VarBr id -- 'x, ''T
944 instance OutputableBndr id => Outputable (HsBracket id) where
948 pprHsBracket :: OutputableBndr id => HsBracket id -> SDoc
949 pprHsBracket (ExpBr e) = thBrackets empty (ppr e)
950 pprHsBracket (PatBr p) = thBrackets (char 'p') (ppr p)
951 pprHsBracket (DecBr d) = thBrackets (char 'd') (ppr d)
952 pprHsBracket (TypBr t) = thBrackets (char 't') (ppr t)
953 pprHsBracket (VarBr n) = char '\'' <> ppr n
954 -- Infelicity: can't show ' vs '', because
955 -- we can't ask n what its OccName is, because the
956 -- pretty-printer for HsExpr doesn't ask for NamedThings
957 -- But the pretty-printer for names will show the OccName class
959 thBrackets :: SDoc -> SDoc -> SDoc
960 thBrackets pp_kind pp_body = char '[' <> pp_kind <> char '|' <+>
961 pp_body <+> ptext SLIT("|]")
964 %************************************************************************
966 \subsection{Enumerations and list comprehensions}
968 %************************************************************************
973 | FromThen (LHsExpr id)
975 | FromTo (LHsExpr id)
977 | FromThenTo (LHsExpr id)
983 instance OutputableBndr id => Outputable (ArithSeqInfo id) where
984 ppr (From e1) = hcat [ppr e1, pp_dotdot]
985 ppr (FromThen e1 e2) = hcat [ppr e1, comma, space, ppr e2, pp_dotdot]
986 ppr (FromTo e1 e3) = hcat [ppr e1, pp_dotdot, ppr e3]
987 ppr (FromThenTo e1 e2 e3)
988 = hcat [ppr e1, comma, space, ppr e2, pp_dotdot, ppr e3]
991 pp_dotdot = ptext SLIT(" .. ")
995 %************************************************************************
997 \subsection{HsMatchCtxt}
999 %************************************************************************
1002 data HsMatchContext id -- Context of a Match
1003 = FunRhs id Bool -- Function binding for f; True <=> written infix
1004 | CaseAlt -- Guard on a case alternative
1005 | LambdaExpr -- Pattern of a lambda
1006 | ProcExpr -- Pattern of a proc
1007 | PatBindRhs -- Pattern binding
1008 | RecUpd -- Record update [used only in DsExpr to
1009 -- tell matchWrapper what sort of
1010 -- runtime error message to generate]
1011 | StmtCtxt (HsStmtContext id) -- Pattern of a do-stmt or list comprehension
1014 data HsStmtContext id
1017 | MDoExpr PostTcTable -- Recursive do-expression
1018 -- (tiresomely, it needs table
1019 -- of its return/bind ops)
1020 | PArrComp -- Parallel array comprehension
1021 | PatGuard (HsMatchContext id) -- Pattern guard for specified thing
1022 | ParStmtCtxt (HsStmtContext id) -- A branch of a parallel stmt
1023 | TransformStmtCtxt (HsStmtContext id) -- A branch of a transform stmt
1027 isDoExpr :: HsStmtContext id -> Bool
1028 isDoExpr DoExpr = True
1029 isDoExpr (MDoExpr _) = True
1032 isListCompExpr :: HsStmtContext id -> Bool
1033 isListCompExpr ListComp = True
1034 isListCompExpr PArrComp = True
1035 isListCompExpr _ = False
1039 matchSeparator :: HsMatchContext id -> SDoc
1040 matchSeparator (FunRhs {}) = ptext SLIT("=")
1041 matchSeparator CaseAlt = ptext SLIT("->")
1042 matchSeparator LambdaExpr = ptext SLIT("->")
1043 matchSeparator ProcExpr = ptext SLIT("->")
1044 matchSeparator PatBindRhs = ptext SLIT("=")
1045 matchSeparator (StmtCtxt _) = ptext SLIT("<-")
1046 matchSeparator RecUpd = panic "unused"
1050 pprMatchContext :: Outputable id => HsMatchContext id -> SDoc
1051 pprMatchContext (FunRhs fun _) = ptext SLIT("the definition of")
1052 <+> quotes (ppr fun)
1053 pprMatchContext CaseAlt = ptext SLIT("a case alternative")
1054 pprMatchContext RecUpd = ptext SLIT("a record-update construct")
1055 pprMatchContext PatBindRhs = ptext SLIT("a pattern binding")
1056 pprMatchContext LambdaExpr = ptext SLIT("a lambda abstraction")
1057 pprMatchContext ProcExpr = ptext SLIT("an arrow abstraction")
1058 pprMatchContext (StmtCtxt ctxt) = ptext SLIT("a pattern binding in")
1059 $$ pprStmtContext ctxt
1061 pprStmtContext :: Outputable id => HsStmtContext id -> SDoc
1062 pprStmtContext (ParStmtCtxt c)
1063 = sep [ptext SLIT("a parallel branch of"), pprStmtContext c]
1064 pprStmtContext (TransformStmtCtxt c)
1065 = sep [ptext SLIT("a transformed branch of"), pprStmtContext c]
1066 pprStmtContext (PatGuard ctxt)
1067 = ptext SLIT("a pattern guard for") $$ pprMatchContext ctxt
1068 pprStmtContext DoExpr = ptext SLIT("a 'do' expression")
1069 pprStmtContext (MDoExpr _) = ptext SLIT("an 'mdo' expression")
1070 pprStmtContext ListComp = ptext SLIT("a list comprehension")
1071 pprStmtContext PArrComp = ptext SLIT("an array comprehension")
1074 pprMatchRhsContext (FunRhs fun) = ptext SLIT("a right-hand side of function") <+> quotes (ppr fun)
1075 pprMatchRhsContext CaseAlt = ptext SLIT("the body of a case alternative")
1076 pprMatchRhsContext PatBindRhs = ptext SLIT("the right-hand side of a pattern binding")
1077 pprMatchRhsContext LambdaExpr = ptext SLIT("the body of a lambda")
1078 pprMatchRhsContext ProcExpr = ptext SLIT("the body of a proc")
1079 pprMatchRhsContext other = panic "pprMatchRhsContext" -- RecUpd, StmtCtxt
1081 -- Used for the result statement of comprehension
1082 -- e.g. the 'e' in [ e | ... ]
1083 -- or the 'r' in f x = r
1084 pprStmtResultContext (PatGuard ctxt) = pprMatchRhsContext ctxt
1085 pprStmtResultContext other = ptext SLIT("the result of") <+> pprStmtContext other
1088 -- Used to generate the string for a *runtime* error message
1089 matchContextErrString :: Outputable id => HsMatchContext id -> String
1090 matchContextErrString (FunRhs fun _) = "function " ++ showSDoc (ppr fun)
1091 matchContextErrString CaseAlt = "case"
1092 matchContextErrString PatBindRhs = "pattern binding"
1093 matchContextErrString RecUpd = "record update"
1094 matchContextErrString LambdaExpr = "lambda"
1095 matchContextErrString ProcExpr = "proc"
1096 matchContextErrString (StmtCtxt (ParStmtCtxt c)) = matchContextErrString (StmtCtxt c)
1097 matchContextErrString (StmtCtxt (TransformStmtCtxt c)) = matchContextErrString (StmtCtxt c)
1098 matchContextErrString (StmtCtxt (PatGuard _)) = "pattern guard"
1099 matchContextErrString (StmtCtxt DoExpr) = "'do' expression"
1100 matchContextErrString (StmtCtxt (MDoExpr _)) = "'mdo' expression"
1101 matchContextErrString (StmtCtxt ListComp) = "list comprehension"
1102 matchContextErrString (StmtCtxt PArrComp) = "array comprehension"