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) -- Application
99 -- Operator applications:
100 -- NB Bracketed ops such as (+) come out as Vars.
102 -- NB We need an expr for the operator in an OpApp/Section since
103 -- the typechecker may need to apply the operator to a few types.
105 | OpApp (LHsExpr id) -- left operand
106 (LHsExpr id) -- operator
107 Fixity -- Renamer adds fixity; bottom until then
108 (LHsExpr id) -- right operand
110 | NegApp (LHsExpr id) -- negated expr
111 (SyntaxExpr id) -- Name of 'negate'
113 | HsPar (LHsExpr id) -- parenthesised expr
115 | SectionL (LHsExpr id) -- operand
116 (LHsExpr id) -- operator
117 | SectionR (LHsExpr id) -- operator
118 (LHsExpr id) -- operand
120 | HsCase (LHsExpr id)
123 | HsIf (LHsExpr id) -- predicate
124 (LHsExpr id) -- then part
125 (LHsExpr id) -- else part
127 | HsLet (HsLocalBinds id) -- let(rec)
130 | HsDo (HsStmtContext Name) -- The parameterisation is unimportant
131 -- because in this context we never use
132 -- the PatGuard or ParStmt variant
133 [LStmt id] -- "do":one or more stmts
134 (LHsExpr id) -- The body; the last expression in the 'do'
135 -- of [ body | ... ] in a list comp
136 PostTcType -- Type of the whole expression
138 | ExplicitList -- syntactic list
139 PostTcType -- Gives type of components of list
142 | ExplicitPArr -- syntactic parallel array: [:e1, ..., en:]
143 PostTcType -- type of elements of the parallel array
146 | ExplicitTuple -- tuple
148 -- NB: Unit is ExplicitTuple []
149 -- for tuples, we can get the types
150 -- direct from the components
154 -- Record construction
155 | RecordCon (Located id) -- The constructor. After type checking
156 -- it's the dataConWrapId of the constructor
157 PostTcExpr -- Data con Id applied to type args
161 | RecordUpd (LHsExpr id)
163 [DataCon] -- Filled in by the type checker to the *non-empty*
164 -- list of DataCons that have 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, not the family tycon
169 | ExprWithTySig -- e :: type
173 | ExprWithTySigOut -- TRANSLATION
175 (LHsType Name) -- Retain the signature for round-tripping purposes
177 | ArithSeq -- arithmetic sequence
181 | PArrSeq -- arith. sequence for parallel array
182 PostTcExpr -- [:e1..e2:] or [:e1, e2..e3:]
185 | HsSCC FastString -- "set cost centre" (_scc_) annotation
186 (LHsExpr id) -- expr whose cost is to be measured
188 | HsCoreAnn FastString -- hdaume: core annotation
191 -----------------------------------------------------------
192 -- MetaHaskell Extensions
194 | HsBracket (HsBracket id)
196 | HsBracketOut (HsBracket Name) -- Output of the type checker is the *original*
197 [PendingSplice] -- renamed expression, plus *typechecked* splices
198 -- to be pasted back in by the desugarer
200 | HsSpliceE (HsSplice id)
202 -----------------------------------------------------------
203 -- Arrow notation extension
205 | HsProc (LPat id) -- arrow abstraction, proc
206 (LHsCmdTop id) -- body of the abstraction
207 -- always has an empty stack
209 ---------------------------------------
210 -- The following are commands, not expressions proper
212 | HsArrApp -- Arrow tail, or arrow application (f -< arg)
213 (LHsExpr id) -- arrow expression, f
214 (LHsExpr id) -- input expression, arg
215 PostTcType -- type of the arrow expressions f,
216 -- of the form a t t', where arg :: t
217 HsArrAppType -- higher-order (-<<) or first-order (-<)
218 Bool -- True => right-to-left (f -< arg)
219 -- False => left-to-right (arg >- f)
221 | HsArrForm -- Command formation, (| e cmd1 .. cmdn |)
222 (LHsExpr id) -- the operator
223 -- after type-checking, a type abstraction to be
224 -- applied to the type of the local environment tuple
225 (Maybe Fixity) -- fixity (filled in by the renamer), for forms that
226 -- were converted from OpApp's by the renamer
227 [LHsCmdTop id] -- argument commands
230 ---------------------------------------
231 -- Haskell program coverage (Hpc) Support
234 Int -- module-local tick number
235 [id] -- variables in scope
236 (LHsExpr id) -- sub-expression
239 Int -- module-local tick number for True
240 Int -- module-local tick number for False
241 (LHsExpr id) -- sub-expression
243 | HsTickPragma -- A pragma introduced tick
244 (FastString,(Int,Int),(Int,Int)) -- external span for this tick
247 ---------------------------------------
248 -- These constructors only appear temporarily in the parser.
249 -- The renamer translates them into the Right Thing.
251 | EWildPat -- wildcard
253 | EAsPat (Located id) -- as pattern
256 | EViewPat (LHsExpr id) -- view pattern
259 | ELazyPat (LHsExpr id) -- ~ pattern
261 | HsType (LHsType id) -- Explicit type argument; e.g f {| Int |} x y
263 ---------------------------------------
264 -- Finally, HsWrap appears only in typechecker output
266 | HsWrap HsWrapper -- TRANSLATION
269 type PendingSplice = (Name, LHsExpr Id) -- Typechecked splices, waiting to be
270 -- pasted back in by the desugarer
273 A @Dictionary@, unless of length 0 or 1, becomes a tuple. A
274 @ClassDictLam dictvars methods expr@ is, therefore:
276 \ x -> case x of ( dictvars-and-methods-tuple ) -> expr
280 instance OutputableBndr id => Outputable (HsExpr id) where
281 ppr expr = pprExpr expr
285 -----------------------
286 -- pprExpr, pprLExpr, pprBinds call pprDeeper;
287 -- the underscore versions do not
288 pprLExpr :: OutputableBndr id => LHsExpr id -> SDoc
289 pprLExpr (L _ e) = pprExpr e
291 pprExpr :: OutputableBndr id => HsExpr id -> SDoc
292 pprExpr e | isAtomicHsExpr e || isQuietHsExpr e = ppr_expr e
293 | otherwise = pprDeeper (ppr_expr e)
295 isQuietHsExpr :: HsExpr id -> Bool
296 -- Parentheses do display something, but it gives little info and
297 -- if we go deeper when we go inside them then we get ugly things
299 isQuietHsExpr (HsPar _) = True
300 -- applications don't display anything themselves
301 isQuietHsExpr (HsApp _ _) = True
302 isQuietHsExpr (OpApp _ _ _ _) = True
303 isQuietHsExpr _ = False
305 pprBinds :: (OutputableBndr idL, OutputableBndr idR) => HsLocalBindsLR idL idR -> SDoc
306 pprBinds b = pprDeeper (ppr b)
308 -----------------------
309 ppr_lexpr :: OutputableBndr id => LHsExpr id -> SDoc
310 ppr_lexpr e = ppr_expr (unLoc e)
312 ppr_expr :: OutputableBndr id => HsExpr id -> SDoc
313 ppr_expr (HsVar v) = pprHsVar v
314 ppr_expr (HsIPVar v) = ppr v
315 ppr_expr (HsLit lit) = ppr lit
316 ppr_expr (HsOverLit lit) = ppr lit
317 ppr_expr (HsPar e) = parens (ppr_lexpr e)
319 ppr_expr (HsCoreAnn s e)
320 = vcat [ptext SLIT("HsCoreAnn") <+> ftext s, ppr_lexpr e]
322 ppr_expr (HsApp e1 e2)
323 = let (fun, args) = collect_args e1 [e2] in
324 hang (ppr_lexpr fun) 2 (sep (map pprParendExpr args))
326 collect_args (L _ (HsApp fun arg)) args = collect_args fun (arg:args)
327 collect_args fun args = (fun, args)
329 ppr_expr (OpApp e1 op _ e2)
331 HsVar v -> pp_infixly v
334 pp_e1 = pprDebugParendExpr e1 -- In debug mode, add parens
335 pp_e2 = pprDebugParendExpr e2 -- to make precedence clear
338 = hang (ppr op) 2 (sep [pp_e1, pp_e2])
341 = sep [nest 2 pp_e1, pprInfix v, nest 2 pp_e2]
343 ppr_expr (NegApp e _) = char '-' <+> pprDebugParendExpr e
345 ppr_expr (SectionL expr op)
347 HsVar v -> pp_infixly v
350 pp_expr = pprDebugParendExpr expr
352 pp_prefixly = hang (hsep [text " \\ x_ ->", ppr op])
353 4 (hsep [pp_expr, ptext SLIT("x_ )")])
354 pp_infixly v = (sep [pp_expr, pprInfix v])
356 ppr_expr (SectionR op expr)
358 HsVar v -> pp_infixly v
361 pp_expr = pprDebugParendExpr expr
363 pp_prefixly = hang (hsep [text "( \\ x_ ->", ppr op, ptext SLIT("x_")])
364 4 ((<>) pp_expr rparen)
366 = (sep [pprInfix v, pp_expr])
368 ppr_expr (HsLam matches :: HsExpr id)
369 = pprMatches (LambdaExpr :: HsMatchContext id) matches
371 ppr_expr (HsCase expr matches :: HsExpr id)
372 = sep [ sep [ptext SLIT("case"), nest 4 (ppr expr), ptext SLIT("of")],
373 nest 2 (pprMatches (CaseAlt :: HsMatchContext id) matches) ]
375 ppr_expr (HsIf e1 e2 e3)
376 = sep [hsep [ptext SLIT("if"), nest 2 (ppr e1), ptext SLIT("then")],
381 -- special case: let ... in let ...
382 ppr_expr (HsLet binds expr@(L _ (HsLet _ _)))
383 = sep [hang (ptext SLIT("let")) 2 (hsep [pprBinds binds, ptext SLIT("in")]),
386 ppr_expr (HsLet binds expr)
387 = sep [hang (ptext SLIT("let")) 2 (pprBinds binds),
388 hang (ptext SLIT("in")) 2 (ppr expr)]
390 ppr_expr (HsDo do_or_list_comp stmts body _) = pprDo do_or_list_comp stmts body
392 ppr_expr (ExplicitList _ exprs)
393 = brackets (pprDeeperList fsep (punctuate comma (map ppr_lexpr exprs)))
395 ppr_expr (ExplicitPArr _ exprs)
396 = pa_brackets (pprDeeperList fsep (punctuate comma (map ppr_lexpr exprs)))
398 ppr_expr (ExplicitTuple exprs boxity)
399 = tupleParens boxity (sep (punctuate comma (map ppr_lexpr exprs)))
401 ppr_expr (RecordCon con_id _ rbinds)
402 = hang (ppr con_id) 2 (ppr rbinds)
404 ppr_expr (RecordUpd aexp rbinds _ _ _)
405 = hang (pprParendExpr aexp) 2 (ppr rbinds)
407 ppr_expr (ExprWithTySig expr sig)
408 = hang (nest 2 (ppr_lexpr expr) <+> dcolon)
410 ppr_expr (ExprWithTySigOut expr sig)
411 = hang (nest 2 (ppr_lexpr expr) <+> dcolon)
414 ppr_expr (ArithSeq _ info) = brackets (ppr info)
415 ppr_expr (PArrSeq _ info) = pa_brackets (ppr info)
417 ppr_expr EWildPat = char '_'
418 ppr_expr (ELazyPat e) = char '~' <> pprParendExpr e
419 ppr_expr (EAsPat v e) = ppr v <> char '@' <> pprParendExpr e
420 ppr_expr (EViewPat p e) = ppr p <+> ptext SLIT("->") <+> ppr e
422 ppr_expr (HsSCC lbl expr)
423 = sep [ ptext SLIT("_scc_") <+> doubleQuotes (ftext lbl), pprParendExpr expr ]
425 ppr_expr (HsWrap co_fn e) = pprHsWrapper (pprExpr e) co_fn
426 ppr_expr (HsType id) = ppr id
428 ppr_expr (HsSpliceE s) = pprSplice s
429 ppr_expr (HsBracket b) = pprHsBracket b
430 ppr_expr (HsBracketOut e []) = ppr e
431 ppr_expr (HsBracketOut e ps) = ppr e $$ ptext SLIT("pending") <+> ppr ps
433 ppr_expr (HsProc pat (L _ (HsCmdTop cmd _ _ _)))
434 = hsep [ptext SLIT("proc"), ppr pat, ptext SLIT("->"), ppr cmd]
436 ppr_expr (HsTick tickId vars exp)
437 = hcat [ptext SLIT("tick<"), ppr tickId,ptext SLIT(">("), hsep (map pprHsVar vars), ppr exp,ptext SLIT(")")]
438 ppr_expr (HsBinTick tickIdTrue tickIdFalse exp)
439 = hcat [ptext SLIT("bintick<"),
444 ppr exp,ptext SLIT(")")]
445 ppr_expr (HsTickPragma externalSrcLoc exp)
446 = hcat [ptext SLIT("tickpragma<"), ppr externalSrcLoc,ptext SLIT(">("), ppr exp,ptext SLIT(")")]
448 ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp True)
449 = hsep [ppr_lexpr arrow, ptext SLIT("-<"), ppr_lexpr arg]
450 ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp False)
451 = hsep [ppr_lexpr arg, ptext SLIT(">-"), ppr_lexpr arrow]
452 ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp True)
453 = hsep [ppr_lexpr arrow, ptext SLIT("-<<"), ppr_lexpr arg]
454 ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp False)
455 = hsep [ppr_lexpr arg, ptext SLIT(">>-"), ppr_lexpr arrow]
457 ppr_expr (HsArrForm (L _ (HsVar v)) (Just _) [arg1, arg2])
458 = sep [pprCmdArg (unLoc arg1), hsep [pprInfix v, pprCmdArg (unLoc arg2)]]
459 ppr_expr (HsArrForm op _ args)
460 = hang (ptext SLIT("(|") <> ppr_lexpr op)
461 4 (sep (map (pprCmdArg.unLoc) args) <> ptext SLIT("|)"))
463 pprCmdArg :: OutputableBndr id => HsCmdTop id -> SDoc
464 pprCmdArg (HsCmdTop cmd@(L _ (HsArrForm _ Nothing [])) _ _ _)
466 pprCmdArg (HsCmdTop cmd _ _ _)
467 = parens (ppr_lexpr cmd)
469 -- Put a var in backquotes if it's not an operator already
470 pprInfix :: Outputable name => name -> SDoc
471 pprInfix v | isOperator ppr_v = ppr_v
472 | otherwise = char '`' <> ppr_v <> char '`'
476 -- add parallel array brackets around a document
478 pa_brackets :: SDoc -> SDoc
479 pa_brackets p = ptext SLIT("[:") <> p <> ptext SLIT(":]")
482 HsSyn records exactly where the user put parens, with HsPar.
483 So generally speaking we print without adding any parens.
484 However, some code is internally generated, and in some places
485 parens are absolutely required; so for these places we use
486 pprParendExpr (but don't print double parens of course).
488 For operator applications we don't add parens, because the oprerator
489 fixities should do the job, except in debug mode (-dppr-debug) so we
490 can see the structure of the parse tree.
493 pprDebugParendExpr :: OutputableBndr id => LHsExpr id -> SDoc
494 pprDebugParendExpr expr
495 = getPprStyle (\sty ->
496 if debugStyle sty then pprParendExpr expr
499 pprParendExpr :: OutputableBndr id => LHsExpr id -> SDoc
502 pp_as_was = pprLExpr expr
503 -- Using pprLExpr makes sure that we go 'deeper'
504 -- I think that is usually (always?) right
508 HsOverLit _ -> pp_as_was
510 HsIPVar _ -> pp_as_was
511 ExplicitList _ _ -> pp_as_was
512 ExplicitPArr _ _ -> pp_as_was
513 ExplicitTuple _ _ -> pp_as_was
515 HsBracket _ -> pp_as_was
516 HsBracketOut _ [] -> pp_as_was
518 | isListCompExpr sc -> pp_as_was
519 _ -> parens pp_as_was
521 isAtomicHsExpr :: HsExpr id -> Bool -- A single token
522 isAtomicHsExpr (HsVar {}) = True
523 isAtomicHsExpr (HsLit {}) = True
524 isAtomicHsExpr (HsOverLit {}) = True
525 isAtomicHsExpr (HsIPVar {}) = True
526 isAtomicHsExpr (HsWrap _ e) = isAtomicHsExpr e
527 isAtomicHsExpr (HsPar e) = isAtomicHsExpr (unLoc e)
528 isAtomicHsExpr _ = False
531 %************************************************************************
533 \subsection{Commands (in arrow abstractions)}
535 %************************************************************************
537 We re-use HsExpr to represent these.
540 type HsCmd id = HsExpr id
542 type LHsCmd id = LHsExpr id
544 data HsArrAppType = HsHigherOrderApp | HsFirstOrderApp
547 The legal constructors for commands are:
549 = HsArrApp ... -- as above
551 | HsArrForm ... -- as above
556 | HsLam (Match id) -- kappa
558 -- the renamer turns this one into HsArrForm
559 | OpApp (HsExpr id) -- left operand
560 (HsCmd id) -- operator
561 Fixity -- Renamer adds fixity; bottom until then
562 (HsCmd id) -- right operand
564 | HsPar (HsCmd id) -- parenthesised command
567 [Match id] -- bodies are HsCmd's
570 | HsIf (HsExpr id) -- predicate
571 (HsCmd id) -- then part
572 (HsCmd id) -- else part
575 | HsLet (HsLocalBinds id) -- let(rec)
578 | HsDo (HsStmtContext Name) -- The parameterisation is unimportant
579 -- because in this context we never use
580 -- the PatGuard or ParStmt variant
581 [Stmt id] -- HsExpr's are really HsCmd's
582 PostTcType -- Type of the whole expression
585 Top-level command, introducing a new arrow.
586 This may occur inside a proc (where the stack is empty) or as an
587 argument of a command-forming operator.
590 type LHsCmdTop id = Located (HsCmdTop id)
593 = HsCmdTop (LHsCmd id)
594 [PostTcType] -- types of inputs on the command's stack
595 PostTcType -- return type of the command
597 -- after type checking:
598 -- names used in the command's desugaring
601 %************************************************************************
603 \subsection{Record binds}
605 %************************************************************************
608 type HsRecordBinds id = HsRecFields id (LHsExpr id)
613 %************************************************************************
615 \subsection{@Match@, @GRHSs@, and @GRHS@ datatypes}
617 %************************************************************************
619 @Match@es are sets of pattern bindings and right hand sides for
620 functions, patterns or case branches. For example, if a function @g@
626 then \tr{g} has two @Match@es: @(x,y) = y@ and @((x:ys),y) = y+1@.
628 It is always the case that each element of an @[Match]@ list has the
629 same number of @pats@s inside it. This corresponds to saying that
630 a function defined by pattern matching must have the same number of
631 patterns in each equation.
636 [LMatch id] -- The alternatives
637 PostTcType -- The type is the type of the entire group
638 -- t1 -> ... -> tn -> tr
639 -- where there are n patterns
641 type LMatch id = Located (Match id)
645 [LPat id] -- The patterns
646 (Maybe (LHsType id)) -- A type signature for the result of the match
647 -- Nothing after typechecking
650 matchGroupArity :: MatchGroup id -> Arity
651 matchGroupArity (MatchGroup [] _)
652 = panic "matchGroupArity" -- MatchGroup is never empty
653 matchGroupArity (MatchGroup (match:matches) _)
654 = ASSERT( all ((== n_pats) . length . hsLMatchPats) matches )
655 -- Assertion just checks that all the matches have the same number of pats
658 n_pats = length (hsLMatchPats match)
660 hsLMatchPats :: LMatch id -> [LPat id]
661 hsLMatchPats (L _ (Match pats _ _)) = pats
663 -- GRHSs are used both for pattern bindings and for Matches
665 = GRHSs [LGRHS id] -- Guarded RHSs
666 (HsLocalBinds id) -- The where clause
668 type LGRHS id = Located (GRHS id)
670 data GRHS id = GRHS [LStmt id] -- Guards
671 (LHsExpr id) -- Right hand side
674 We know the list must have at least one @Match@ in it.
677 pprMatches :: (OutputableBndr idL, OutputableBndr idR) => HsMatchContext idL -> MatchGroup idR -> SDoc
678 pprMatches ctxt (MatchGroup matches _)
679 = vcat (map (pprMatch ctxt) (map unLoc matches))
680 -- Don't print the type; it's only
681 -- a place-holder before typechecking
683 -- Exported to HsBinds, which can't see the defn of HsMatchContext
684 pprFunBind :: (OutputableBndr idL, OutputableBndr idR) => idL -> Bool -> MatchGroup idR -> SDoc
685 pprFunBind fun inf matches = pprMatches (FunRhs fun inf) matches
687 -- Exported to HsBinds, which can't see the defn of HsMatchContext
688 pprPatBind :: (OutputableBndr bndr, OutputableBndr id)
689 => LPat bndr -> GRHSs id -> SDoc
690 pprPatBind pat (grhss :: GRHSs id) = sep [ppr pat, nest 4 (pprGRHSs (PatBindRhs :: HsMatchContext id) grhss)]
693 pprMatch :: (OutputableBndr idL, OutputableBndr idR) => HsMatchContext idL -> Match idR -> SDoc
694 pprMatch ctxt (Match pats maybe_ty grhss)
695 = herald <+> sep [sep (map ppr other_pats),
697 nest 2 (pprGRHSs ctxt grhss)]
702 | not is_infix -> (ppr fun, pats)
704 -- Not pprBndr; the AbsBinds will
705 -- have printed the signature
707 | null pats3 -> (pp_infix, [])
710 | otherwise -> (parens pp_infix, pats3)
713 (pat1:pat2:pats3) = pats
714 pp_infix = ppr pat1 <+> ppr fun <+> ppr pat2
716 LambdaExpr -> (char '\\', pats)
719 ppr_maybe_ty = case maybe_ty of
720 Just ty -> dcolon <+> ppr ty
724 pprGRHSs :: (OutputableBndr idL, OutputableBndr idR) => HsMatchContext idL -> GRHSs idR -> SDoc
725 pprGRHSs ctxt (GRHSs grhss binds)
726 = vcat (map (pprGRHS ctxt . unLoc) grhss)
727 $$ if isEmptyLocalBinds binds then empty
728 else text "where" $$ nest 4 (pprBinds binds)
730 pprGRHS :: (OutputableBndr idL, OutputableBndr idR) => HsMatchContext idL -> GRHS idR -> SDoc
732 pprGRHS ctxt (GRHS [] expr)
735 pprGRHS ctxt (GRHS guards expr)
736 = sep [char '|' <+> interpp'SP guards, pp_rhs ctxt expr]
738 pp_rhs :: OutputableBndr idR => HsMatchContext idL -> LHsExpr idR -> SDoc
739 pp_rhs ctxt rhs = matchSeparator ctxt <+> pprDeeper (ppr rhs)
742 %************************************************************************
744 \subsection{Do stmts and list comprehensions}
746 %************************************************************************
749 type LStmt id = Located (StmtLR id id)
750 type LStmtLR idL idR = Located (StmtLR idL idR)
752 type Stmt id = StmtLR id id
754 data GroupByClause id = GroupByNothing (LHsExpr id) -- Using expression, i.e. "then group using f" ==> GroupByNothing f
755 | GroupBySomething (Either (LHsExpr id) (SyntaxExpr id))
757 -- "then group using f by e" ==> GroupBySomething (Left f) e
758 -- "then group by e" ==> GroupBySomething (Right _) e: in this case the expression is filled in by the renamer
760 -- The SyntaxExprs in here are used *only* for do-notation, which
761 -- has rebindable syntax. Otherwise they are unused.
763 = BindStmt (LPat idL)
765 (SyntaxExpr idR) -- The (>>=) operator
766 (SyntaxExpr idR) -- The fail operator
767 -- The fail operator is noSyntaxExpr
768 -- if the pattern match can't fail
770 | ExprStmt (LHsExpr idR)
771 (SyntaxExpr idR) -- The (>>) operator
772 PostTcType -- Element type of the RHS (used for arrows)
774 | LetStmt (HsLocalBindsLR idL idR)
776 -- ParStmts only occur in a list comprehension
777 | ParStmt [([LStmt idL], [idR])]
778 -- After renaming, the ids are the binders bound by the stmts and used after them
780 | TransformStmt ([LStmt idL], [idR]) (LHsExpr idR) (Maybe (LHsExpr idR))
781 -- After renaming, the IDs are the binders occurring within this transform statement that are used after it
782 -- "qs, then f by e" ==> TransformStmt (qs, binders) f (Just e)
783 -- "qs, then f" ==> TransformStmt (qs, binders) f Nothing
785 | GroupStmt ([LStmt idL], [(idR, idR)]) (GroupByClause idR)
786 -- After renaming, the IDs are the binders occurring within this transform statement that are used after it
787 -- which are paired with the names which they group over in statements
789 -- Recursive statement (see Note [RecStmt] below)
790 | RecStmt [LStmtLR idL idR]
791 --- The next two fields are only valid after renaming
792 [idR] -- The ids are a subset of the variables bound by the stmts
793 -- that are used in stmts that follow the RecStmt
795 [idR] -- Ditto, but these variables are the "recursive" ones, that
796 -- are used before they are bound in the stmts of the RecStmt
797 -- From a type-checking point of view, these ones have to be monomorphic
799 --- These fields are only valid after typechecking
800 [PostTcExpr] -- These expressions correspond
801 -- 1-to-1 with the "recursive" [id], and are the expresions that
802 -- should be returned by the recursion. They may not quite be the
803 -- Ids themselves, because the Id may be *polymorphic*, but
804 -- the returned thing has to be *monomorphic*.
805 (DictBinds idR) -- Method bindings of Ids bound by the RecStmt,
806 -- and used afterwards
809 ExprStmts are a bit tricky, because what they mean
810 depends on the context. Consider the following contexts:
812 A do expression of type (m res_ty)
813 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
814 * ExprStmt E any_ty: do { ....; E; ... }
816 Translation: E >> ...
818 A list comprehensions of type [elt_ty]
819 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
820 * ExprStmt E Bool: [ .. | .... E ]
822 [ .. | .... | ..., E | ... ]
824 Translation: if E then fail else ...
826 A guard list, guarding a RHS of type rhs_ty
827 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
828 * ExprStmt E Bool: f x | ..., E, ... = ...rhs...
830 Translation: if E then fail else ...
832 Array comprehensions are handled like list comprehensions -=chak
839 , RecStmt [a::forall a. a -> a, b]
841 [ BindStmt b (return x)
847 Here, the RecStmt binds a,b,c; but
848 - Only a,b are used in the stmts *following* the RecStmt,
849 This 'a' is *polymorphic'
850 - Only a,c are used in the stmts *inside* the RecStmt
851 *before* their bindings
852 This 'a' is monomorphic
854 Nota Bene: the two a's have different types, even though they
859 instance (OutputableBndr idL, OutputableBndr idR) => Outputable (StmtLR idL idR) where
860 ppr stmt = pprStmt stmt
862 pprStmt :: (OutputableBndr idL, OutputableBndr idR) => (StmtLR idL idR) -> SDoc
863 pprStmt (BindStmt pat expr _ _) = hsep [ppr pat, ptext SLIT("<-"), ppr expr]
864 pprStmt (LetStmt binds) = hsep [ptext SLIT("let"), pprBinds binds]
865 pprStmt (ExprStmt expr _ _) = ppr expr
866 pprStmt (ParStmt stmtss) = hsep (map (\stmts -> ptext SLIT("| ") <> ppr stmts) stmtss)
867 pprStmt (TransformStmt (stmts, _) usingExpr maybeByExpr)
868 = (hsep [stmtsDoc, ptext SLIT("then"), ppr usingExpr, byExprDoc])
869 where stmtsDoc = interpp'SP stmts
870 byExprDoc = maybe empty (\byExpr -> hsep [ptext SLIT("by"), ppr byExpr]) maybeByExpr
871 pprStmt (GroupStmt (stmts, _) groupByClause) = (hsep [stmtsDoc, ptext SLIT("then group"), pprGroupByClause groupByClause])
872 where stmtsDoc = interpp'SP stmts
873 pprStmt (RecStmt segment _ _ _ _) = ptext SLIT("rec") <+> braces (vcat (map ppr segment))
875 pprGroupByClause :: (OutputableBndr id) => GroupByClause id -> SDoc
876 pprGroupByClause (GroupByNothing usingExpr) = hsep [ptext SLIT("using"), ppr usingExpr]
877 pprGroupByClause (GroupBySomething eitherUsingExpr byExpr) = hsep [ptext SLIT("by"), ppr byExpr, usingExprDoc]
878 where usingExprDoc = either (\usingExpr -> hsep [ptext SLIT("using"), ppr usingExpr]) (const empty) eitherUsingExpr
880 pprDo :: OutputableBndr id => HsStmtContext any -> [LStmt id] -> LHsExpr id -> SDoc
881 pprDo DoExpr stmts body = ptext SLIT("do") <+> pprDeeperList vcat (map ppr stmts ++ [ppr body])
882 pprDo (MDoExpr _) stmts body = ptext SLIT("mdo") <+> pprDeeperList vcat (map ppr stmts ++ [ppr body])
883 pprDo ListComp stmts body = pprComp brackets stmts body
884 pprDo PArrComp stmts body = pprComp pa_brackets stmts body
885 pprDo _ _ _ = panic "pprDo" -- PatGuard, ParStmtCxt
887 pprComp :: OutputableBndr id => (SDoc -> SDoc) -> [LStmt id] -> LHsExpr id -> SDoc
888 pprComp brack quals body
890 hang (ppr body <+> char '|')
894 %************************************************************************
896 Template Haskell quotation brackets
898 %************************************************************************
901 data HsSplice id = HsSplice -- $z or $(f 4)
902 id -- The id is just a unique name to
903 (LHsExpr id) -- identify this splice point
905 instance OutputableBndr id => Outputable (HsSplice id) where
908 pprSplice :: OutputableBndr id => HsSplice id -> SDoc
909 pprSplice (HsSplice n e) = char '$' <> ifPprDebug (brackets (ppr n)) <> pprParendExpr e
912 data HsBracket id = ExpBr (LHsExpr id) -- [| expr |]
913 | PatBr (LPat id) -- [p| pat |]
914 | DecBr (HsGroup id) -- [d| decls |]
915 | TypBr (LHsType id) -- [t| type |]
916 | VarBr id -- 'x, ''T
918 instance OutputableBndr id => Outputable (HsBracket id) where
922 pprHsBracket :: OutputableBndr id => HsBracket id -> SDoc
923 pprHsBracket (ExpBr e) = thBrackets empty (ppr e)
924 pprHsBracket (PatBr p) = thBrackets (char 'p') (ppr p)
925 pprHsBracket (DecBr d) = thBrackets (char 'd') (ppr d)
926 pprHsBracket (TypBr t) = thBrackets (char 't') (ppr t)
927 pprHsBracket (VarBr n) = char '\'' <> ppr n
928 -- Infelicity: can't show ' vs '', because
929 -- we can't ask n what its OccName is, because the
930 -- pretty-printer for HsExpr doesn't ask for NamedThings
931 -- But the pretty-printer for names will show the OccName class
933 thBrackets :: SDoc -> SDoc -> SDoc
934 thBrackets pp_kind pp_body = char '[' <> pp_kind <> char '|' <+>
935 pp_body <+> ptext SLIT("|]")
938 %************************************************************************
940 \subsection{Enumerations and list comprehensions}
942 %************************************************************************
947 | FromThen (LHsExpr id)
949 | FromTo (LHsExpr id)
951 | FromThenTo (LHsExpr id)
957 instance OutputableBndr id => Outputable (ArithSeqInfo id) where
958 ppr (From e1) = hcat [ppr e1, pp_dotdot]
959 ppr (FromThen e1 e2) = hcat [ppr e1, comma, space, ppr e2, pp_dotdot]
960 ppr (FromTo e1 e3) = hcat [ppr e1, pp_dotdot, ppr e3]
961 ppr (FromThenTo e1 e2 e3)
962 = hcat [ppr e1, comma, space, ppr e2, pp_dotdot, ppr e3]
965 pp_dotdot = ptext SLIT(" .. ")
969 %************************************************************************
971 \subsection{HsMatchCtxt}
973 %************************************************************************
976 data HsMatchContext id -- Context of a Match
977 = FunRhs id Bool -- Function binding for f; True <=> written infix
978 | CaseAlt -- Guard on a case alternative
979 | LambdaExpr -- Pattern of a lambda
980 | ProcExpr -- Pattern of a proc
981 | PatBindRhs -- Pattern binding
982 | RecUpd -- Record update [used only in DsExpr to tell matchWrapper
983 -- what sort of runtime error message to generate]
984 | StmtCtxt (HsStmtContext id) -- Pattern of a do-stmt or list comprehension
987 data HsStmtContext id
990 | MDoExpr PostTcTable -- Recursive do-expression
991 -- (tiresomely, it needs table
992 -- of its return/bind ops)
993 | PArrComp -- Parallel array comprehension
994 | PatGuard (HsMatchContext id) -- Pattern guard for specified thing
995 | ParStmtCtxt (HsStmtContext id) -- A branch of a parallel stmt
996 | TransformStmtCtxt (HsStmtContext id) -- A branch of a transform stmt
1000 isDoExpr :: HsStmtContext id -> Bool
1001 isDoExpr DoExpr = True
1002 isDoExpr (MDoExpr _) = True
1005 isListCompExpr :: HsStmtContext id -> Bool
1006 isListCompExpr ListComp = True
1007 isListCompExpr PArrComp = True
1008 isListCompExpr _ = False
1012 matchSeparator :: HsMatchContext id -> SDoc
1013 matchSeparator (FunRhs {}) = ptext SLIT("=")
1014 matchSeparator CaseAlt = ptext SLIT("->")
1015 matchSeparator LambdaExpr = ptext SLIT("->")
1016 matchSeparator ProcExpr = ptext SLIT("->")
1017 matchSeparator PatBindRhs = ptext SLIT("=")
1018 matchSeparator (StmtCtxt _) = ptext SLIT("<-")
1019 matchSeparator RecUpd = panic "unused"
1023 pprMatchContext :: Outputable id => HsMatchContext id -> SDoc
1024 pprMatchContext (FunRhs fun _) = ptext SLIT("the definition of") <+> quotes (ppr fun)
1025 pprMatchContext CaseAlt = ptext SLIT("a case alternative")
1026 pprMatchContext RecUpd = ptext SLIT("a record-update construct")
1027 pprMatchContext PatBindRhs = ptext SLIT("a pattern binding")
1028 pprMatchContext LambdaExpr = ptext SLIT("a lambda abstraction")
1029 pprMatchContext ProcExpr = ptext SLIT("an arrow abstraction")
1030 pprMatchContext (StmtCtxt ctxt) = ptext SLIT("a pattern binding in") $$ pprStmtContext ctxt
1032 pprStmtContext :: Outputable id => HsStmtContext id -> SDoc
1033 pprStmtContext (ParStmtCtxt c) = sep [ptext SLIT("a parallel branch of"), pprStmtContext c]
1034 pprStmtContext (TransformStmtCtxt c) = sep [ptext SLIT("a transformed branch of"), pprStmtContext c]
1035 pprStmtContext (PatGuard ctxt) = ptext SLIT("a pattern guard for") $$ pprMatchContext ctxt
1036 pprStmtContext DoExpr = ptext SLIT("a 'do' expression")
1037 pprStmtContext (MDoExpr _) = ptext SLIT("an 'mdo' expression")
1038 pprStmtContext ListComp = ptext SLIT("a list comprehension")
1039 pprStmtContext PArrComp = ptext SLIT("an array comprehension")
1042 pprMatchRhsContext (FunRhs fun) = ptext SLIT("a right-hand side of function") <+> quotes (ppr fun)
1043 pprMatchRhsContext CaseAlt = ptext SLIT("the body of a case alternative")
1044 pprMatchRhsContext PatBindRhs = ptext SLIT("the right-hand side of a pattern binding")
1045 pprMatchRhsContext LambdaExpr = ptext SLIT("the body of a lambda")
1046 pprMatchRhsContext ProcExpr = ptext SLIT("the body of a proc")
1047 pprMatchRhsContext other = panic "pprMatchRhsContext" -- RecUpd, StmtCtxt
1049 -- Used for the result statement of comprehension
1050 -- e.g. the 'e' in [ e | ... ]
1051 -- or the 'r' in f x = r
1052 pprStmtResultContext (PatGuard ctxt) = pprMatchRhsContext ctxt
1053 pprStmtResultContext other = ptext SLIT("the result of") <+> pprStmtContext other
1056 -- Used to generate the string for a *runtime* error message
1057 matchContextErrString :: Outputable id => HsMatchContext id -> String
1058 matchContextErrString (FunRhs fun _) = "function " ++ showSDoc (ppr fun)
1059 matchContextErrString CaseAlt = "case"
1060 matchContextErrString PatBindRhs = "pattern binding"
1061 matchContextErrString RecUpd = "record update"
1062 matchContextErrString LambdaExpr = "lambda"
1063 matchContextErrString ProcExpr = "proc"
1064 matchContextErrString (StmtCtxt (ParStmtCtxt c)) = matchContextErrString (StmtCtxt c)
1065 matchContextErrString (StmtCtxt (TransformStmtCtxt c)) = matchContextErrString (StmtCtxt c)
1066 matchContextErrString (StmtCtxt (PatGuard _)) = "pattern guard"
1067 matchContextErrString (StmtCtxt DoExpr) = "'do' expression"
1068 matchContextErrString (StmtCtxt (MDoExpr _)) = "'mdo' expression"
1069 matchContextErrString (StmtCtxt ListComp) = "list comprehension"
1070 matchContextErrString (StmtCtxt PArrComp) = "array comprehension"