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 | HsQuasiQuoteE (HsQuasiQuote id)
207 -- See Note [Quasi-quote overview] in TcSplice
209 -----------------------------------------------------------
210 -- Arrow notation extension
212 | HsProc (LPat id) -- arrow abstraction, proc
213 (LHsCmdTop id) -- body of the abstraction
214 -- always has an empty stack
216 ---------------------------------------
217 -- The following are commands, not expressions proper
219 | HsArrApp -- Arrow tail, or arrow application (f -< arg)
220 (LHsExpr id) -- arrow expression, f
221 (LHsExpr id) -- input expression, arg
222 PostTcType -- type of the arrow expressions f,
223 -- of the form a t t', where arg :: t
224 HsArrAppType -- higher-order (-<<) or first-order (-<)
225 Bool -- True => right-to-left (f -< arg)
226 -- False => left-to-right (arg >- f)
228 | HsArrForm -- Command formation, (| e cmd1 .. cmdn |)
229 (LHsExpr id) -- the operator
230 -- after type-checking, a type abstraction to be
231 -- applied to the type of the local environment tuple
232 (Maybe Fixity) -- fixity (filled in by the renamer), for forms that
233 -- were converted from OpApp's by the renamer
234 [LHsCmdTop id] -- argument commands
237 ---------------------------------------
238 -- Haskell program coverage (Hpc) Support
241 Int -- module-local tick number
242 [id] -- variables in scope
243 (LHsExpr id) -- sub-expression
246 Int -- module-local tick number for True
247 Int -- module-local tick number for False
248 (LHsExpr id) -- sub-expression
250 | HsTickPragma -- A pragma introduced tick
251 (FastString,(Int,Int),(Int,Int)) -- external span for this tick
254 ---------------------------------------
255 -- These constructors only appear temporarily in the parser.
256 -- The renamer translates them into the Right Thing.
258 | EWildPat -- wildcard
260 | EAsPat (Located id) -- as pattern
263 | EViewPat (LHsExpr id) -- view pattern
266 | ELazyPat (LHsExpr id) -- ~ pattern
268 | HsType (LHsType id) -- Explicit type argument; e.g f {| Int |} x y
270 ---------------------------------------
271 -- Finally, HsWrap appears only in typechecker output
273 | HsWrap HsWrapper -- TRANSLATION
276 type PendingSplice = (Name, LHsExpr Id) -- Typechecked splices, waiting to be
277 -- pasted back in by the desugarer
280 A @Dictionary@, unless of length 0 or 1, becomes a tuple. A
281 @ClassDictLam dictvars methods expr@ is, therefore:
283 \ x -> case x of ( dictvars-and-methods-tuple ) -> expr
287 instance OutputableBndr id => Outputable (HsExpr id) where
288 ppr expr = pprExpr expr
292 -----------------------
293 -- pprExpr, pprLExpr, pprBinds call pprDeeper;
294 -- the underscore versions do not
295 pprLExpr :: OutputableBndr id => LHsExpr id -> SDoc
296 pprLExpr (L _ e) = pprExpr e
298 pprExpr :: OutputableBndr id => HsExpr id -> SDoc
299 pprExpr e | isAtomicHsExpr e || isQuietHsExpr e = ppr_expr e
300 | otherwise = pprDeeper (ppr_expr e)
302 isQuietHsExpr :: HsExpr id -> Bool
303 -- Parentheses do display something, but it gives little info and
304 -- if we go deeper when we go inside them then we get ugly things
306 isQuietHsExpr (HsPar _) = True
307 -- applications don't display anything themselves
308 isQuietHsExpr (HsApp _ _) = True
309 isQuietHsExpr (OpApp _ _ _ _) = True
310 isQuietHsExpr _ = False
312 pprBinds :: (OutputableBndr idL, OutputableBndr idR)
313 => HsLocalBindsLR idL idR -> SDoc
314 pprBinds b = pprDeeper (ppr b)
316 -----------------------
317 ppr_lexpr :: OutputableBndr id => LHsExpr id -> SDoc
318 ppr_lexpr e = ppr_expr (unLoc e)
320 ppr_expr :: OutputableBndr id => HsExpr id -> SDoc
321 ppr_expr (HsVar v) = pprHsVar v
322 ppr_expr (HsIPVar v) = ppr v
323 ppr_expr (HsLit lit) = ppr lit
324 ppr_expr (HsOverLit lit) = ppr lit
325 ppr_expr (HsPar e) = parens (ppr_lexpr e)
327 ppr_expr (HsCoreAnn s e)
328 = vcat [ptext SLIT("HsCoreAnn") <+> ftext s, ppr_lexpr e]
330 ppr_expr (HsApp e1 e2)
331 = let (fun, args) = collect_args e1 [e2] in
332 hang (ppr_lexpr fun) 2 (sep (map pprParendExpr args))
334 collect_args (L _ (HsApp fun arg)) args = collect_args fun (arg:args)
335 collect_args fun args = (fun, args)
337 ppr_expr (OpApp e1 op _ e2)
339 HsVar v -> pp_infixly v
342 pp_e1 = pprDebugParendExpr e1 -- In debug mode, add parens
343 pp_e2 = pprDebugParendExpr e2 -- to make precedence clear
346 = hang (ppr op) 2 (sep [pp_e1, pp_e2])
349 = sep [nest 2 pp_e1, pprInfix v, nest 2 pp_e2]
351 ppr_expr (NegApp e _) = char '-' <+> pprDebugParendExpr e
353 ppr_expr (SectionL expr op)
355 HsVar v -> pp_infixly v
358 pp_expr = pprDebugParendExpr expr
360 pp_prefixly = hang (hsep [text " \\ x_ ->", ppr op])
361 4 (hsep [pp_expr, ptext SLIT("x_ )")])
362 pp_infixly v = (sep [pp_expr, pprInfix v])
364 ppr_expr (SectionR op expr)
366 HsVar v -> pp_infixly v
369 pp_expr = pprDebugParendExpr expr
371 pp_prefixly = hang (hsep [text "( \\ x_ ->", ppr op, ptext SLIT("x_")])
372 4 ((<>) pp_expr rparen)
374 = (sep [pprInfix v, pp_expr])
376 --avoid using PatternSignatures for stage1 code portability
377 ppr_expr exprType@(HsLam matches)
378 = pprMatches (LambdaExpr `asTypeOf` idType exprType) matches
379 where idType :: HsExpr id -> HsMatchContext id; idType = undefined
381 ppr_expr exprType@(HsCase expr matches)
382 = sep [ sep [ptext SLIT("case"), nest 4 (ppr expr), ptext SLIT("of")],
383 nest 2 (pprMatches (CaseAlt `asTypeOf` idType exprType) matches) ]
384 where idType :: HsExpr id -> HsMatchContext id; idType = undefined
386 ppr_expr (HsIf e1 e2 e3)
387 = sep [hsep [ptext SLIT("if"), nest 2 (ppr e1), ptext SLIT("then")],
392 -- special case: let ... in let ...
393 ppr_expr (HsLet binds expr@(L _ (HsLet _ _)))
394 = sep [hang (ptext SLIT("let")) 2 (hsep [pprBinds binds, ptext SLIT("in")]),
397 ppr_expr (HsLet binds expr)
398 = sep [hang (ptext SLIT("let")) 2 (pprBinds binds),
399 hang (ptext SLIT("in")) 2 (ppr expr)]
401 ppr_expr (HsDo do_or_list_comp stmts body _) = pprDo do_or_list_comp stmts body
403 ppr_expr (ExplicitList _ exprs)
404 = brackets (pprDeeperList fsep (punctuate comma (map ppr_lexpr exprs)))
406 ppr_expr (ExplicitPArr _ exprs)
407 = pa_brackets (pprDeeperList fsep (punctuate comma (map ppr_lexpr exprs)))
409 ppr_expr (ExplicitTuple exprs boxity)
410 = tupleParens boxity (sep (punctuate comma (map ppr_lexpr exprs)))
412 ppr_expr (RecordCon con_id _ rbinds)
413 = hang (ppr con_id) 2 (ppr rbinds)
415 ppr_expr (RecordUpd aexp rbinds _ _ _)
416 = hang (pprParendExpr aexp) 2 (ppr rbinds)
418 ppr_expr (ExprWithTySig expr sig)
419 = hang (nest 2 (ppr_lexpr expr) <+> dcolon)
421 ppr_expr (ExprWithTySigOut expr sig)
422 = hang (nest 2 (ppr_lexpr expr) <+> dcolon)
425 ppr_expr (ArithSeq _ info) = brackets (ppr info)
426 ppr_expr (PArrSeq _ info) = pa_brackets (ppr info)
428 ppr_expr EWildPat = char '_'
429 ppr_expr (ELazyPat e) = char '~' <> pprParendExpr e
430 ppr_expr (EAsPat v e) = ppr v <> char '@' <> pprParendExpr e
431 ppr_expr (EViewPat p e) = ppr p <+> ptext SLIT("->") <+> ppr e
433 ppr_expr (HsSCC lbl expr)
434 = sep [ ptext SLIT("_scc_") <+> doubleQuotes (ftext lbl),
437 ppr_expr (HsWrap co_fn e) = pprHsWrapper (pprExpr e) co_fn
438 ppr_expr (HsType id) = ppr id
440 ppr_expr (HsSpliceE s) = pprSplice s
441 ppr_expr (HsBracket b) = pprHsBracket b
442 ppr_expr (HsBracketOut e []) = ppr e
443 ppr_expr (HsBracketOut e ps) = ppr e $$ ptext SLIT("pending") <+> ppr ps
444 ppr_expr (HsQuasiQuoteE (HsQuasiQuote name quoter _ quote))
445 = char '$' <> brackets (ppr name) <>
446 ptext SLIT("[:") <> ppr quoter <> ptext SLIT("|") <>
447 ppr quote <> ptext SLIT("|]")
449 ppr_expr (HsProc pat (L _ (HsCmdTop cmd _ _ _)))
450 = hsep [ptext SLIT("proc"), ppr pat, ptext SLIT("->"), ppr cmd]
452 ppr_expr (HsTick tickId vars exp)
453 = hcat [ptext SLIT("tick<"),
456 hsep (map pprHsVar vars),
459 ppr_expr (HsBinTick tickIdTrue tickIdFalse exp)
460 = hcat [ptext SLIT("bintick<"),
465 ppr exp,ptext SLIT(")")]
466 ppr_expr (HsTickPragma externalSrcLoc exp)
467 = hcat [ptext SLIT("tickpragma<"),
473 ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp True)
474 = hsep [ppr_lexpr arrow, ptext SLIT("-<"), ppr_lexpr arg]
475 ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp False)
476 = hsep [ppr_lexpr arg, ptext SLIT(">-"), ppr_lexpr arrow]
477 ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp True)
478 = hsep [ppr_lexpr arrow, ptext SLIT("-<<"), ppr_lexpr arg]
479 ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp False)
480 = hsep [ppr_lexpr arg, ptext SLIT(">>-"), ppr_lexpr arrow]
482 ppr_expr (HsArrForm (L _ (HsVar v)) (Just _) [arg1, arg2])
483 = sep [pprCmdArg (unLoc arg1), hsep [pprInfix v, pprCmdArg (unLoc arg2)]]
484 ppr_expr (HsArrForm op _ args)
485 = hang (ptext SLIT("(|") <> ppr_lexpr op)
486 4 (sep (map (pprCmdArg.unLoc) args) <> ptext SLIT("|)"))
488 pprCmdArg :: OutputableBndr id => HsCmdTop id -> SDoc
489 pprCmdArg (HsCmdTop cmd@(L _ (HsArrForm _ Nothing [])) _ _ _)
491 pprCmdArg (HsCmdTop cmd _ _ _)
492 = parens (ppr_lexpr cmd)
494 -- Put a var in backquotes if it's not an operator already
495 pprInfix :: Outputable name => name -> SDoc
496 pprInfix v | isOperator ppr_v = ppr_v
497 | otherwise = char '`' <> ppr_v <> char '`'
500 -- add parallel array brackets around a document
502 pa_brackets :: SDoc -> SDoc
503 pa_brackets p = ptext SLIT("[:") <> p <> ptext SLIT(":]")
506 HsSyn records exactly where the user put parens, with HsPar.
507 So generally speaking we print without adding any parens.
508 However, some code is internally generated, and in some places
509 parens are absolutely required; so for these places we use
510 pprParendExpr (but don't print double parens of course).
512 For operator applications we don't add parens, because the oprerator
513 fixities should do the job, except in debug mode (-dppr-debug) so we
514 can see the structure of the parse tree.
517 pprDebugParendExpr :: OutputableBndr id => LHsExpr id -> SDoc
518 pprDebugParendExpr expr
519 = getPprStyle (\sty ->
520 if debugStyle sty then pprParendExpr expr
523 pprParendExpr :: OutputableBndr id => LHsExpr id -> SDoc
526 pp_as_was = pprLExpr expr
527 -- Using pprLExpr makes sure that we go 'deeper'
528 -- I think that is usually (always?) right
532 HsOverLit _ -> pp_as_was
534 HsIPVar _ -> pp_as_was
535 ExplicitList _ _ -> pp_as_was
536 ExplicitPArr _ _ -> pp_as_was
537 ExplicitTuple _ _ -> pp_as_was
539 HsBracket _ -> pp_as_was
540 HsBracketOut _ [] -> pp_as_was
542 | isListCompExpr sc -> pp_as_was
543 _ -> parens pp_as_was
545 isAtomicHsExpr :: HsExpr id -> Bool -- A single token
546 isAtomicHsExpr (HsVar {}) = True
547 isAtomicHsExpr (HsLit {}) = True
548 isAtomicHsExpr (HsOverLit {}) = True
549 isAtomicHsExpr (HsIPVar {}) = True
550 isAtomicHsExpr (HsWrap _ e) = isAtomicHsExpr e
551 isAtomicHsExpr (HsPar e) = isAtomicHsExpr (unLoc e)
552 isAtomicHsExpr _ = False
555 %************************************************************************
557 \subsection{Commands (in arrow abstractions)}
559 %************************************************************************
561 We re-use HsExpr to represent these.
564 type HsCmd id = HsExpr id
566 type LHsCmd id = LHsExpr id
568 data HsArrAppType = HsHigherOrderApp | HsFirstOrderApp
571 The legal constructors for commands are:
573 = HsArrApp ... -- as above
575 | HsArrForm ... -- as above
580 | HsLam (Match id) -- kappa
582 -- the renamer turns this one into HsArrForm
583 | OpApp (HsExpr id) -- left operand
584 (HsCmd id) -- operator
585 Fixity -- Renamer adds fixity; bottom until then
586 (HsCmd id) -- right operand
588 | HsPar (HsCmd id) -- parenthesised command
591 [Match id] -- bodies are HsCmd's
594 | HsIf (HsExpr id) -- predicate
595 (HsCmd id) -- then part
596 (HsCmd id) -- else part
599 | HsLet (HsLocalBinds id) -- let(rec)
602 | HsDo (HsStmtContext Name) -- The parameterisation is unimportant
603 -- because in this context we never use
604 -- the PatGuard or ParStmt variant
605 [Stmt id] -- HsExpr's are really HsCmd's
606 PostTcType -- Type of the whole expression
609 Top-level command, introducing a new arrow.
610 This may occur inside a proc (where the stack is empty) or as an
611 argument of a command-forming operator.
614 type LHsCmdTop id = Located (HsCmdTop id)
617 = HsCmdTop (LHsCmd id)
618 [PostTcType] -- types of inputs on the command's stack
619 PostTcType -- return type of the command
620 (SyntaxTable id) -- after type checking:
621 -- names used in the command's desugaring
624 %************************************************************************
626 \subsection{Record binds}
628 %************************************************************************
631 type HsRecordBinds id = HsRecFields id (LHsExpr id)
636 %************************************************************************
638 \subsection{@Match@, @GRHSs@, and @GRHS@ datatypes}
640 %************************************************************************
642 @Match@es are sets of pattern bindings and right hand sides for
643 functions, patterns or case branches. For example, if a function @g@
649 then \tr{g} has two @Match@es: @(x,y) = y@ and @((x:ys),y) = y+1@.
651 It is always the case that each element of an @[Match]@ list has the
652 same number of @pats@s inside it. This corresponds to saying that
653 a function defined by pattern matching must have the same number of
654 patterns in each equation.
659 [LMatch id] -- The alternatives
660 PostTcType -- The type is the type of the entire group
661 -- t1 -> ... -> tn -> tr
662 -- where there are n patterns
664 type LMatch id = Located (Match id)
668 [LPat id] -- The patterns
669 (Maybe (LHsType id)) -- A type signature for the result of the match
670 -- Nothing after typechecking
673 matchGroupArity :: MatchGroup id -> Arity
674 matchGroupArity (MatchGroup [] _)
675 = panic "matchGroupArity" -- MatchGroup is never empty
676 matchGroupArity (MatchGroup (match:matches) _)
677 = ASSERT( all ((== n_pats) . length . hsLMatchPats) matches )
678 -- Assertion just checks that all the matches have the same number of pats
681 n_pats = length (hsLMatchPats match)
683 hsLMatchPats :: LMatch id -> [LPat id]
684 hsLMatchPats (L _ (Match pats _ _)) = pats
686 -- GRHSs are used both for pattern bindings and for Matches
688 = GRHSs [LGRHS id] -- Guarded RHSs
689 (HsLocalBinds id) -- The where clause
691 type LGRHS id = Located (GRHS id)
693 data GRHS id = GRHS [LStmt id] -- Guards
694 (LHsExpr id) -- Right hand side
697 We know the list must have at least one @Match@ in it.
700 pprMatches :: (OutputableBndr idL, OutputableBndr idR) => HsMatchContext idL -> MatchGroup idR -> SDoc
701 pprMatches ctxt (MatchGroup matches _)
702 = vcat (map (pprMatch ctxt) (map unLoc matches))
703 -- Don't print the type; it's only a place-holder before typechecking
705 -- Exported to HsBinds, which can't see the defn of HsMatchContext
706 pprFunBind :: (OutputableBndr idL, OutputableBndr idR) => idL -> Bool -> MatchGroup idR -> SDoc
707 pprFunBind fun inf matches = pprMatches (FunRhs fun inf) matches
709 -- Exported to HsBinds, which can't see the defn of HsMatchContext
710 pprPatBind :: (OutputableBndr bndr, OutputableBndr id)
711 => LPat bndr -> GRHSs id -> SDoc
712 pprPatBind pat ty@(grhss)
713 = sep [ppr pat, nest 4 (pprGRHSs (PatBindRhs `asTypeOf` idType ty) grhss)]
714 --avoid using PatternSignatures for stage1 code portability
715 where idType :: GRHSs id -> HsMatchContext id; idType = undefined
718 pprMatch :: (OutputableBndr idL, OutputableBndr idR) => HsMatchContext idL -> Match idR -> SDoc
719 pprMatch ctxt (Match pats maybe_ty grhss)
720 = herald <+> sep [sep (map ppr other_pats),
722 nest 2 (pprGRHSs ctxt grhss)]
727 | not is_infix -> (ppr fun, pats)
729 -- Not pprBndr; the AbsBinds will
730 -- have printed the signature
732 | null pats3 -> (pp_infix, [])
735 | otherwise -> (parens pp_infix, pats3)
738 (pat1:pat2:pats3) = pats
739 pp_infix = ppr pat1 <+> ppr fun <+> ppr pat2
741 LambdaExpr -> (char '\\', pats)
744 ppr_maybe_ty = case maybe_ty of
745 Just ty -> dcolon <+> ppr ty
749 pprGRHSs :: (OutputableBndr idL, OutputableBndr idR)
750 => HsMatchContext idL -> GRHSs idR -> SDoc
751 pprGRHSs ctxt (GRHSs grhss binds)
752 = vcat (map (pprGRHS ctxt . unLoc) grhss)
753 $$ if isEmptyLocalBinds binds then empty
754 else text "where" $$ nest 4 (pprBinds binds)
756 pprGRHS :: (OutputableBndr idL, OutputableBndr idR)
757 => HsMatchContext idL -> GRHS idR -> SDoc
759 pprGRHS ctxt (GRHS [] expr)
762 pprGRHS ctxt (GRHS guards expr)
763 = sep [char '|' <+> interpp'SP guards, pp_rhs ctxt expr]
765 pp_rhs :: OutputableBndr idR => HsMatchContext idL -> LHsExpr idR -> SDoc
766 pp_rhs ctxt rhs = matchSeparator ctxt <+> pprDeeper (ppr rhs)
769 %************************************************************************
771 \subsection{Do stmts and list comprehensions}
773 %************************************************************************
776 type LStmt id = Located (StmtLR id id)
777 type LStmtLR idL idR = Located (StmtLR idL idR)
779 type Stmt id = StmtLR id id
781 data GroupByClause id
782 = GroupByNothing (LHsExpr id) -- Using expression, i.e.
783 -- "then group using f" ==> GroupByNothing f
784 | GroupBySomething (Either (LHsExpr id) (SyntaxExpr id)) (LHsExpr id)
785 -- "then group using f by e" ==> GroupBySomething (Left f) e
786 -- "then group by e" ==> GroupBySomething (Right _) e: in
787 -- this case the expression is filled
790 -- The SyntaxExprs in here are used *only* for do-notation, which
791 -- has rebindable syntax. Otherwise they are unused.
793 = BindStmt (LPat idL)
795 (SyntaxExpr idR) -- The (>>=) operator
796 (SyntaxExpr idR) -- The fail operator
797 -- The fail operator is noSyntaxExpr
798 -- if the pattern match can't fail
800 | ExprStmt (LHsExpr idR)
801 (SyntaxExpr idR) -- The (>>) operator
802 PostTcType -- Element type of the RHS (used for arrows)
804 | LetStmt (HsLocalBindsLR idL idR)
806 -- ParStmts only occur in a list comprehension
807 | ParStmt [([LStmt idL], [idR])]
808 -- After renaming, the ids are the binders bound by the stmts and used
811 | TransformStmt ([LStmt idL], [idR]) (LHsExpr idR) (Maybe (LHsExpr idR))
812 -- After renaming, the IDs are the binders occurring within this
813 -- transform statement that are used after it
814 -- "qs, then f by e" ==> TransformStmt (qs, binders) f (Just e)
815 -- "qs, then f" ==> TransformStmt (qs, binders) f Nothing
817 | GroupStmt ([LStmt idL], [(idR, idR)]) (GroupByClause idR)
818 -- After renaming, the IDs are the binders occurring within this
819 -- transform statement that are used after it which are paired with
820 -- the names which they group over in statements
822 -- Recursive statement (see Note [RecStmt] below)
823 | RecStmt [LStmtLR idL idR]
824 --- The next two fields are only valid after renaming
825 [idR] -- The ids are a subset of the variables bound by the
826 -- stmts that are used in stmts that follow the RecStmt
828 [idR] -- Ditto, but these variables are the "recursive" ones,
829 -- that are used before they are bound in the stmts of
830 -- the RecStmt. From a type-checking point of view,
831 -- these ones have to be monomorphic
833 --- These fields are only valid after typechecking
834 [PostTcExpr] -- These expressions correspond 1-to-1 with
835 -- the "recursive" [id], and are the
836 -- expressions that should be returned by
838 -- They may not quite be the Ids themselves,
839 -- because the Id may be *polymorphic*, but
840 -- the returned thing has to be *monomorphic*.
841 (DictBinds idR) -- Method bindings of Ids bound by the
842 -- RecStmt, and used afterwards
845 ExprStmts are a bit tricky, because what they mean
846 depends on the context. Consider the following contexts:
848 A do expression of type (m res_ty)
849 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
850 * ExprStmt E any_ty: do { ....; E; ... }
852 Translation: E >> ...
854 A list comprehensions of type [elt_ty]
855 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
856 * ExprStmt E Bool: [ .. | .... E ]
858 [ .. | .... | ..., E | ... ]
860 Translation: if E then fail else ...
862 A guard list, guarding a RHS of type rhs_ty
863 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
864 * ExprStmt E Bool: f x | ..., E, ... = ...rhs...
866 Translation: if E then fail else ...
868 Array comprehensions are handled like list comprehensions -=chak
875 , RecStmt [a::forall a. a -> a, b]
877 [ BindStmt b (return x)
883 Here, the RecStmt binds a,b,c; but
884 - Only a,b are used in the stmts *following* the RecStmt,
885 This 'a' is *polymorphic'
886 - Only a,c are used in the stmts *inside* the RecStmt
887 *before* their bindings
888 This 'a' is monomorphic
890 Nota Bene: the two a's have different types, even though they
895 instance (OutputableBndr idL, OutputableBndr idR) => Outputable (StmtLR idL idR) where
896 ppr stmt = pprStmt stmt
898 pprStmt :: (OutputableBndr idL, OutputableBndr idR) => (StmtLR idL idR) -> SDoc
899 pprStmt (BindStmt pat expr _ _) = hsep [ppr pat, ptext SLIT("<-"), ppr expr]
900 pprStmt (LetStmt binds) = hsep [ptext SLIT("let"), pprBinds binds]
901 pprStmt (ExprStmt expr _ _) = ppr expr
902 pprStmt (ParStmt stmtss) = hsep (map doStmts stmtss)
903 where doStmts stmts = ptext SLIT("| ") <> ppr stmts
904 pprStmt (TransformStmt (stmts, _) usingExpr maybeByExpr)
905 = (hsep [stmtsDoc, ptext SLIT("then"), ppr usingExpr, byExprDoc])
906 where stmtsDoc = interpp'SP stmts
907 byExprDoc = maybe empty (\byExpr -> hsep [ptext SLIT("by"), ppr byExpr]) maybeByExpr
908 pprStmt (GroupStmt (stmts, _) groupByClause) = (hsep [stmtsDoc, ptext SLIT("then group"), pprGroupByClause groupByClause])
909 where stmtsDoc = interpp'SP stmts
910 pprStmt (RecStmt segment _ _ _ _) = ptext SLIT("rec") <+> braces (vcat (map ppr segment))
912 pprGroupByClause :: (OutputableBndr id) => GroupByClause id -> SDoc
913 pprGroupByClause (GroupByNothing usingExpr) = hsep [ptext SLIT("using"), ppr usingExpr]
914 pprGroupByClause (GroupBySomething eitherUsingExpr byExpr) = hsep [ptext SLIT("by"), ppr byExpr, usingExprDoc]
915 where usingExprDoc = either (\usingExpr -> hsep [ptext SLIT("using"), ppr usingExpr]) (const empty) eitherUsingExpr
917 pprDo :: OutputableBndr id => HsStmtContext any -> [LStmt id] -> LHsExpr id -> SDoc
918 pprDo DoExpr stmts body = ptext SLIT("do") <+> pprDeeperList vcat (map ppr stmts ++ [ppr body])
919 pprDo (MDoExpr _) stmts body = ptext SLIT("mdo") <+> pprDeeperList vcat (map ppr stmts ++ [ppr body])
920 pprDo ListComp stmts body = pprComp brackets stmts body
921 pprDo PArrComp stmts body = pprComp pa_brackets stmts body
922 pprDo _ _ _ = panic "pprDo" -- PatGuard, ParStmtCxt
924 pprComp :: OutputableBndr id => (SDoc -> SDoc) -> [LStmt id] -> LHsExpr id -> SDoc
925 pprComp brack quals body
927 hang (ppr body <+> char '|')
931 %************************************************************************
933 Template Haskell quotation brackets
935 %************************************************************************
938 data HsSplice id = HsSplice -- $z or $(f 4)
939 id -- The id is just a unique name to
940 (LHsExpr id) -- identify this splice point
942 instance OutputableBndr id => Outputable (HsSplice id) where
945 pprSplice :: OutputableBndr id => HsSplice id -> SDoc
946 pprSplice (HsSplice n e)
947 = char '$' <> ifPprDebug (brackets (ppr n)) <> pprParendExpr e
950 data HsBracket id = ExpBr (LHsExpr id) -- [| expr |]
951 | PatBr (LPat id) -- [p| pat |]
952 | DecBr (HsGroup id) -- [d| decls |]
953 | TypBr (LHsType id) -- [t| type |]
954 | VarBr id -- 'x, ''T
956 instance OutputableBndr id => Outputable (HsBracket id) where
960 pprHsBracket :: OutputableBndr id => HsBracket id -> SDoc
961 pprHsBracket (ExpBr e) = thBrackets empty (ppr e)
962 pprHsBracket (PatBr p) = thBrackets (char 'p') (ppr p)
963 pprHsBracket (DecBr d) = thBrackets (char 'd') (ppr d)
964 pprHsBracket (TypBr t) = thBrackets (char 't') (ppr t)
965 pprHsBracket (VarBr n) = char '\'' <> ppr n
966 -- Infelicity: can't show ' vs '', because
967 -- we can't ask n what its OccName is, because the
968 -- pretty-printer for HsExpr doesn't ask for NamedThings
969 -- But the pretty-printer for names will show the OccName class
971 thBrackets :: SDoc -> SDoc -> SDoc
972 thBrackets pp_kind pp_body = char '[' <> pp_kind <> char '|' <+>
973 pp_body <+> ptext SLIT("|]")
976 %************************************************************************
978 \subsection{Enumerations and list comprehensions}
980 %************************************************************************
985 | FromThen (LHsExpr id)
987 | FromTo (LHsExpr id)
989 | FromThenTo (LHsExpr id)
995 instance OutputableBndr id => Outputable (ArithSeqInfo id) where
996 ppr (From e1) = hcat [ppr e1, pp_dotdot]
997 ppr (FromThen e1 e2) = hcat [ppr e1, comma, space, ppr e2, pp_dotdot]
998 ppr (FromTo e1 e3) = hcat [ppr e1, pp_dotdot, ppr e3]
999 ppr (FromThenTo e1 e2 e3)
1000 = hcat [ppr e1, comma, space, ppr e2, pp_dotdot, ppr e3]
1003 pp_dotdot = ptext SLIT(" .. ")
1007 %************************************************************************
1009 \subsection{HsMatchCtxt}
1011 %************************************************************************
1014 data HsMatchContext id -- Context of a Match
1015 = FunRhs id Bool -- Function binding for f; True <=> written infix
1016 | CaseAlt -- Guard on a case alternative
1017 | LambdaExpr -- Pattern of a lambda
1018 | ProcExpr -- Pattern of a proc
1019 | PatBindRhs -- Pattern binding
1020 | RecUpd -- Record update [used only in DsExpr to
1021 -- tell matchWrapper what sort of
1022 -- runtime error message to generate]
1023 | StmtCtxt (HsStmtContext id) -- Pattern of a do-stmt or list comprehension
1026 data HsStmtContext id
1029 | MDoExpr PostTcTable -- Recursive do-expression
1030 -- (tiresomely, it needs table
1031 -- of its return/bind ops)
1032 | PArrComp -- Parallel array comprehension
1033 | PatGuard (HsMatchContext id) -- Pattern guard for specified thing
1034 | ParStmtCtxt (HsStmtContext id) -- A branch of a parallel stmt
1035 | TransformStmtCtxt (HsStmtContext id) -- A branch of a transform stmt
1039 isDoExpr :: HsStmtContext id -> Bool
1040 isDoExpr DoExpr = True
1041 isDoExpr (MDoExpr _) = True
1044 isListCompExpr :: HsStmtContext id -> Bool
1045 isListCompExpr ListComp = True
1046 isListCompExpr PArrComp = True
1047 isListCompExpr _ = False
1051 matchSeparator :: HsMatchContext id -> SDoc
1052 matchSeparator (FunRhs {}) = ptext SLIT("=")
1053 matchSeparator CaseAlt = ptext SLIT("->")
1054 matchSeparator LambdaExpr = ptext SLIT("->")
1055 matchSeparator ProcExpr = ptext SLIT("->")
1056 matchSeparator PatBindRhs = ptext SLIT("=")
1057 matchSeparator (StmtCtxt _) = ptext SLIT("<-")
1058 matchSeparator RecUpd = panic "unused"
1062 pprMatchContext :: Outputable id => HsMatchContext id -> SDoc
1063 pprMatchContext (FunRhs fun _) = ptext SLIT("the definition of")
1064 <+> quotes (ppr fun)
1065 pprMatchContext CaseAlt = ptext SLIT("a case alternative")
1066 pprMatchContext RecUpd = ptext SLIT("a record-update construct")
1067 pprMatchContext PatBindRhs = ptext SLIT("a pattern binding")
1068 pprMatchContext LambdaExpr = ptext SLIT("a lambda abstraction")
1069 pprMatchContext ProcExpr = ptext SLIT("an arrow abstraction")
1070 pprMatchContext (StmtCtxt ctxt) = ptext SLIT("a pattern binding in")
1071 $$ pprStmtContext ctxt
1073 pprStmtContext :: Outputable id => HsStmtContext id -> SDoc
1074 pprStmtContext (ParStmtCtxt c)
1075 = sep [ptext SLIT("a parallel branch of"), pprStmtContext c]
1076 pprStmtContext (TransformStmtCtxt c)
1077 = sep [ptext SLIT("a transformed branch of"), pprStmtContext c]
1078 pprStmtContext (PatGuard ctxt)
1079 = ptext SLIT("a pattern guard for") $$ pprMatchContext ctxt
1080 pprStmtContext DoExpr = ptext SLIT("a 'do' expression")
1081 pprStmtContext (MDoExpr _) = ptext SLIT("an 'mdo' expression")
1082 pprStmtContext ListComp = ptext SLIT("a list comprehension")
1083 pprStmtContext PArrComp = ptext SLIT("an array comprehension")
1086 pprMatchRhsContext (FunRhs fun) = ptext SLIT("a right-hand side of function") <+> quotes (ppr fun)
1087 pprMatchRhsContext CaseAlt = ptext SLIT("the body of a case alternative")
1088 pprMatchRhsContext PatBindRhs = ptext SLIT("the right-hand side of a pattern binding")
1089 pprMatchRhsContext LambdaExpr = ptext SLIT("the body of a lambda")
1090 pprMatchRhsContext ProcExpr = ptext SLIT("the body of a proc")
1091 pprMatchRhsContext other = panic "pprMatchRhsContext" -- RecUpd, StmtCtxt
1093 -- Used for the result statement of comprehension
1094 -- e.g. the 'e' in [ e | ... ]
1095 -- or the 'r' in f x = r
1096 pprStmtResultContext (PatGuard ctxt) = pprMatchRhsContext ctxt
1097 pprStmtResultContext other = ptext SLIT("the result of") <+> pprStmtContext other
1100 -- Used to generate the string for a *runtime* error message
1101 matchContextErrString :: Outputable id => HsMatchContext id -> String
1102 matchContextErrString (FunRhs fun _) = "function " ++ showSDoc (ppr fun)
1103 matchContextErrString CaseAlt = "case"
1104 matchContextErrString PatBindRhs = "pattern binding"
1105 matchContextErrString RecUpd = "record update"
1106 matchContextErrString LambdaExpr = "lambda"
1107 matchContextErrString ProcExpr = "proc"
1108 matchContextErrString (StmtCtxt (ParStmtCtxt c)) = matchContextErrString (StmtCtxt c)
1109 matchContextErrString (StmtCtxt (TransformStmtCtxt c)) = matchContextErrString (StmtCtxt c)
1110 matchContextErrString (StmtCtxt (PatGuard _)) = "pattern guard"
1111 matchContextErrString (StmtCtxt DoExpr) = "'do' expression"
1112 matchContextErrString (StmtCtxt (MDoExpr _)) = "'mdo' expression"
1113 matchContextErrString (StmtCtxt ListComp) = "list comprehension"
1114 matchContextErrString (StmtCtxt PArrComp) = "array comprehension"