2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[HsExpr]{Abstract Haskell syntax: expressions}
9 #include "HsVersions.h"
12 import HsDecls ( HsGroup )
13 import HsBinds ( HsBinds(..), nullBinds )
14 import HsPat ( Pat(..), HsConDetails(..) )
15 import HsLit ( HsLit(..), HsOverLit )
16 import HsTypes ( HsType, PostTcType, SyntaxName, placeHolderType )
17 import HsImpExp ( isOperator, pprHsVar )
20 import Type ( Type, pprParendType )
21 import Var ( TyVar, Id )
23 import DataCon ( DataCon )
24 import BasicTypes ( IPName, Boxity, tupleParens, Fixity(..) )
25 import SrcLoc ( SrcLoc, generatedSrcLoc )
31 %************************************************************************
33 Some useful helpers for constructing expressions
35 %************************************************************************
38 mkHsApps f xs = foldl HsApp (HsVar f) xs
39 mkHsVarApps f xs = foldl HsApp (HsVar f) (map HsVar xs)
41 mkHsIntLit n = HsLit (HsInt n)
42 mkHsString s = HsString (mkFastString s)
44 mkConPat con vars = ConPatIn con (PrefixCon (map VarPat vars))
45 mkNullaryConPat con = ConPatIn con (PrefixCon [])
47 mkSimpleHsAlt :: Pat id -> HsExpr id -> Match id
48 -- A simple lambda with a single pattern, no binds, no guards; pre-typechecking
49 mkSimpleHsAlt pat expr
50 = mkSimpleMatch [pat] expr placeHolderType generatedSrcLoc
52 mkSimpleMatch :: [Pat id] -> HsExpr id -> Type -> SrcLoc -> Match id
53 mkSimpleMatch pats rhs rhs_ty locn
54 = Match pats Nothing (GRHSs (unguardedRHS rhs locn) EmptyBinds rhs_ty)
56 unguardedRHS :: HsExpr id -> SrcLoc -> [GRHS id]
57 unguardedRHS rhs loc = [GRHS [ResultStmt rhs loc] loc]
59 glueBindsOnGRHSs :: HsBinds id -> GRHSs id -> GRHSs id
60 glueBindsOnGRHSs EmptyBinds grhss = grhss
61 glueBindsOnGRHSs binds1 (GRHSs grhss binds2 ty)
62 = GRHSs grhss (binds1 `ThenBinds` binds2) ty
66 %************************************************************************
68 \subsection{Expressions proper}
70 %************************************************************************
74 = HsVar id -- variable
75 | HsIPVar (IPName id) -- implicit parameter
76 | HsOverLit HsOverLit -- Overloaded literals; eliminated by type checker
77 | HsLit HsLit -- Simple (non-overloaded) literals
79 | HsLam (Match id) -- lambda
80 | HsApp (HsExpr id) -- application
83 -- Operator applications:
84 -- NB Bracketed ops such as (+) come out as Vars.
86 -- NB We need an expr for the operator in an OpApp/Section since
87 -- the typechecker may need to apply the operator to a few types.
89 | OpApp (HsExpr id) -- left operand
90 (HsExpr id) -- operator
91 Fixity -- Renamer adds fixity; bottom until then
92 (HsExpr id) -- right operand
94 -- We preserve prefix negation and parenthesis for the precedence parser.
95 -- They are eventually removed by the type checker.
97 | NegApp (HsExpr id) -- negated expr
98 SyntaxName -- Name of 'negate' (see RnEnv.lookupSyntaxName)
100 | HsPar (HsExpr id) -- parenthesised expr
102 | SectionL (HsExpr id) -- operand
103 (HsExpr id) -- operator
104 | SectionR (HsExpr id) -- operator
105 (HsExpr id) -- operand
111 | HsIf (HsExpr id) -- predicate
112 (HsExpr id) -- then part
113 (HsExpr id) -- else part
116 | HsLet (HsBinds id) -- let(rec)
119 | HsDo (HsStmtContext Name) -- The parameterisation is unimportant
120 -- because in this context we never use
121 -- the PatGuard or ParStmt variant
122 [Stmt id] -- "do":one or more stmts
123 (ReboundNames id) -- Ids for [return,fail,>>=,>>]
124 PostTcType -- Type of the whole expression
127 | ExplicitList -- syntactic list
128 PostTcType -- Gives type of components of list
131 | ExplicitPArr -- syntactic parallel array: [:e1, ..., en:]
132 PostTcType -- type of elements of the parallel array
135 | ExplicitTuple -- tuple
137 -- NB: Unit is ExplicitTuple []
138 -- for tuples, we can get the types
139 -- direct from the components
143 -- Record construction
144 | RecordCon id -- The constructor
147 | RecordConOut DataCon
148 (HsExpr id) -- Data con Id applied to type args
153 | RecordUpd (HsExpr id)
156 | RecordUpdOut (HsExpr id) -- TRANSLATION
157 Type -- Type of *input* record
158 Type -- Type of *result* record (may differ from
159 -- type of input record)
162 | ExprWithTySig -- signature binding
165 | ArithSeqIn -- arithmetic sequence
168 (HsExpr id) -- (typechecked, of course)
170 | PArrSeqIn -- arith. sequence for parallel array
171 (ArithSeqInfo id) -- [:e1..e2:] or [:e1, e2..e3:]
173 (HsExpr id) -- (typechecked, of course)
176 | HsSCC FastString -- "set cost centre" (_scc_) annotation
177 (HsExpr id) -- expr whose cost is to be measured
179 | HsCoreAnn FastString -- hdaume: core annotation
182 -----------------------------------------------------------
183 -- MetaHaskell Extensions
184 | HsBracket (HsBracket id) SrcLoc
186 | HsBracketOut (HsBracket Name) -- Output of the type checker is the *original*
187 [PendingSplice] -- renamed expression, plus *typechecked* splices
188 -- to be pasted back in by the desugarer
190 | HsSplice id (HsExpr id) SrcLoc -- $z or $(f 4)
191 -- The id is just a unique name to
192 -- identify this splice point
194 -----------------------------------------------------------
195 -- Arrow notation extension
197 | HsProc (Pat id) -- arrow abstraction, proc
198 (HsCmdTop id) -- body of the abstraction
199 -- always has an empty stack
202 ---------------------------------------
203 -- The following are commands, not expressions proper
205 | HsArrApp -- Arrow tail, or arrow application (f -< arg)
206 (HsExpr id) -- arrow expression, f
207 (HsExpr id) -- input expression, arg
208 PostTcType -- type of the arrow expressions f,
209 -- of the form a t t', where arg :: t
210 HsArrAppType -- higher-order (-<<) or first-order (-<)
211 Bool -- True => right-to-left (f -< arg)
212 -- False => left-to-right (arg >- f)
215 | HsArrForm -- Command formation, (| e cmd1 .. cmdn |)
216 (HsExpr id) -- the operator
217 -- after type-checking, a type abstraction to be
218 -- applied to the type of the local environment tuple
219 (Maybe Fixity) -- fixity (filled in by the renamer), for forms that
220 -- were converted from OpApp's by the renamer
221 [HsCmdTop id] -- argument commands
227 These constructors only appear temporarily in the parser.
228 The renamer translates them into the Right Thing.
231 | EWildPat -- wildcard
233 | EAsPat id -- as pattern
236 | ELazyPat (HsExpr id) -- ~ pattern
238 | HsType (HsType id) -- Explicit type argument; e.g f {| Int |} x y
241 Everything from here on appears only in typechecker output.
244 | TyLam -- TRANSLATION
247 | TyApp -- TRANSLATION
248 (HsExpr id) -- generated by Spec
251 -- DictLam and DictApp are "inverses"
259 type PendingSplice = (Name, HsExpr Id) -- Typechecked splices, waiting to be
260 -- pasted back in by the desugarer
263 Table of bindings of names used in rebindable syntax.
264 This gets filled in by the renamer.
267 type ReboundNames id = [(Name, HsExpr id)]
268 -- * Before the renamer, this list is empty
270 -- * After the renamer, it takes the form [(std_name, HsVar actual_name)]
271 -- For example, for the 'return' op of a monad
272 -- normal case: (GHC.Base.return, HsVar GHC.Base.return)
273 -- with rebindable syntax: (GHC.Base.return, return_22)
274 -- where return_22 is whatever "return" is in scope
276 -- * After the type checker, it takes the form [(std_name, <expression>)]
277 -- where <expression> is the evidence for the method
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 pprExpr :: OutputableBndr id => HsExpr id -> SDoc
294 pprExpr e = pprDeeper (ppr_expr e)
295 pprBinds b = pprDeeper (ppr b)
297 ppr_expr (HsVar v) = pprHsVar v
298 ppr_expr (HsIPVar v) = ppr v
299 ppr_expr (HsLit lit) = ppr lit
300 ppr_expr (HsOverLit lit) = ppr lit
302 ppr_expr (HsLam match) = pprMatch LambdaExpr match
304 ppr_expr expr@(HsApp e1 e2)
305 = let (fun, args) = collect_args expr [] in
306 (ppr_expr fun) <+> (sep (map pprParendExpr args))
308 collect_args (HsApp fun arg) args = collect_args fun (arg:args)
309 collect_args fun args = (fun, args)
311 ppr_expr (OpApp e1 op fixity e2)
313 HsVar v -> pp_infixly v
316 pp_e1 = pprParendExpr e1 -- Add parens to make precedence clear
317 pp_e2 = pprParendExpr e2
320 = hang (ppr_expr op) 4 (sep [pp_e1, pp_e2])
323 = sep [pp_e1, hsep [pprInfix v, pp_e2]]
325 ppr_expr (NegApp e _) = char '-' <+> pprParendExpr e
327 ppr_expr (HsPar e) = parens (ppr_expr e)
329 ppr_expr (SectionL expr op)
331 HsVar v -> pp_infixly v
334 pp_expr = pprParendExpr expr
336 pp_prefixly = hang (hsep [text " \\ x_ ->", ppr op])
337 4 (hsep [pp_expr, ptext SLIT("x_ )")])
338 pp_infixly v = parens (sep [pp_expr, ppr v])
340 ppr_expr (SectionR op expr)
342 HsVar v -> pp_infixly v
345 pp_expr = pprParendExpr expr
347 pp_prefixly = hang (hsep [text "( \\ x_ ->", ppr op, ptext SLIT("x_")])
348 4 ((<>) pp_expr rparen)
350 = parens (sep [ppr v, pp_expr])
352 ppr_expr (HsCase expr matches _)
353 = sep [ sep [ptext SLIT("case"), nest 4 (pprExpr expr), ptext SLIT("of")],
354 nest 2 (pprMatches CaseAlt matches) ]
356 ppr_expr (HsIf e1 e2 e3 _)
357 = sep [hsep [ptext SLIT("if"), nest 2 (pprExpr e1), ptext SLIT("then")],
362 -- special case: let ... in let ...
363 ppr_expr (HsLet binds expr@(HsLet _ _))
364 = sep [hang (ptext SLIT("let")) 2 (hsep [pprBinds binds, ptext SLIT("in")]),
367 ppr_expr (HsLet binds expr)
368 = sep [hang (ptext SLIT("let")) 2 (pprBinds binds),
369 hang (ptext SLIT("in")) 2 (ppr expr)]
371 ppr_expr (HsDo do_or_list_comp stmts _ _ _) = pprDo do_or_list_comp stmts
373 ppr_expr (ExplicitList _ exprs)
374 = brackets (fsep (punctuate comma (map ppr_expr exprs)))
376 ppr_expr (ExplicitPArr _ exprs)
377 = pa_brackets (fsep (punctuate comma (map ppr_expr exprs)))
379 ppr_expr (ExplicitTuple exprs boxity)
380 = tupleParens boxity (sep (punctuate comma (map ppr_expr exprs)))
382 ppr_expr (RecordCon con_id rbinds)
383 = pp_rbinds (ppr con_id) rbinds
384 ppr_expr (RecordConOut data_con con rbinds)
385 = pp_rbinds (ppr con) rbinds
387 ppr_expr (RecordUpd aexp rbinds)
388 = pp_rbinds (pprParendExpr aexp) rbinds
389 ppr_expr (RecordUpdOut aexp _ _ rbinds)
390 = pp_rbinds (pprParendExpr aexp) rbinds
392 ppr_expr (ExprWithTySig expr sig)
393 = hang (nest 2 (ppr_expr expr) <+> dcolon)
396 ppr_expr (ArithSeqIn info)
397 = brackets (ppr info)
398 ppr_expr (ArithSeqOut expr info)
399 = brackets (ppr info)
401 ppr_expr (PArrSeqIn info)
402 = pa_brackets (ppr info)
403 ppr_expr (PArrSeqOut expr info)
404 = pa_brackets (ppr info)
406 ppr_expr EWildPat = char '_'
407 ppr_expr (ELazyPat e) = char '~' <> pprParendExpr e
408 ppr_expr (EAsPat v e) = ppr v <> char '@' <> pprParendExpr e
410 ppr_expr (HsSCC lbl expr)
411 = sep [ ptext SLIT("_scc_") <+> doubleQuotes (ftext lbl), pprParendExpr expr ]
413 ppr_expr (TyLam tyvars expr)
414 = hang (hsep [ptext SLIT("/\\"),
415 hsep (map (pprBndr LambdaBind) tyvars),
419 ppr_expr (TyApp expr [ty])
420 = hang (ppr_expr expr) 4 (pprParendType ty)
422 ppr_expr (TyApp expr tys)
423 = hang (ppr_expr expr)
424 4 (brackets (interpp'SP tys))
426 ppr_expr (DictLam dictvars expr)
427 = hang (hsep [ptext SLIT("\\{-dict-}"),
428 hsep (map (pprBndr LambdaBind) dictvars),
432 ppr_expr (DictApp expr [dname])
433 = hang (ppr_expr expr) 4 (ppr dname)
435 ppr_expr (DictApp expr dnames)
436 = hang (ppr_expr expr)
437 4 (brackets (interpp'SP dnames))
439 ppr_expr (HsType id) = ppr id
441 ppr_expr (HsSplice n e _) = char '$' <> brackets (ppr n) <> pprParendExpr e
442 ppr_expr (HsBracket b _) = pprHsBracket b
443 ppr_expr (HsBracketOut e ps) = ppr e $$ ptext SLIT("where") <+> ppr ps
445 ppr_expr (HsProc pat (HsCmdTop cmd _ _ _) _)
446 = hsep [ptext SLIT("proc"), ppr pat, ptext SLIT("->"), pprExpr cmd]
448 ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp True _)
449 = hsep [ppr_expr arrow, ptext SLIT("-<"), ppr_expr arg]
450 ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp False _)
451 = hsep [ppr_expr arg, ptext SLIT(">-"), ppr_expr arrow]
452 ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp True _)
453 = hsep [ppr_expr arrow, ptext SLIT("-<<"), ppr_expr arg]
454 ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp False _)
455 = hsep [ppr_expr arg, ptext SLIT(">>-"), ppr_expr arrow]
457 ppr_expr (HsArrForm (HsVar v) (Just _) [arg1, arg2] _)
458 = sep [pprCmdArg arg1, hsep [pprInfix v, pprCmdArg arg2]]
459 ppr_expr (HsArrForm op _ args _)
460 = hang (ptext SLIT("(|") <> ppr_expr op)
461 4 (sep (map pprCmdArg args) <> ptext SLIT("|)"))
463 pprCmdArg :: OutputableBndr id => HsCmdTop id -> SDoc
464 pprCmdArg (HsCmdTop cmd@(HsArrForm _ Nothing [] _) _ _ _) = ppr_expr cmd
465 pprCmdArg (HsCmdTop cmd _ _ _) = parens (ppr_expr cmd)
467 -- Put a var in backquotes if it's not an operator already
468 pprInfix :: Outputable name => name -> SDoc
469 pprInfix v | isOperator ppr_v = ppr_v
470 | otherwise = char '`' <> ppr_v <> char '`'
474 -- add parallel array brackets around a document
476 pa_brackets :: SDoc -> SDoc
477 pa_brackets p = ptext SLIT("[:") <> p <> ptext SLIT(":]")
480 Parenthesize unless very simple:
482 pprParendExpr :: OutputableBndr id => HsExpr id -> SDoc
486 pp_as_was = ppr_expr expr
487 -- Using ppr_expr here avoids the call to 'deeper'
488 -- Not sure if that's always right.
495 HsIPVar _ -> pp_as_was
496 ExplicitList _ _ -> pp_as_was
497 ExplicitPArr _ _ -> pp_as_was
498 ExplicitTuple _ _ -> pp_as_was
501 _ -> parens pp_as_was
504 %************************************************************************
506 \subsection{Commands (in arrow abstractions)}
508 %************************************************************************
510 We re-use HsExpr to represent these.
513 type HsCmd id = HsExpr id
515 data HsArrAppType = HsHigherOrderApp | HsFirstOrderApp
518 The legal constructors for commands are:
520 = HsArrApp ... -- as above
522 | HsArrForm ... -- as above
527 | HsLam (Match id) -- kappa
529 -- the renamer turns this one into HsArrForm
530 | OpApp (HsExpr id) -- left operand
531 (HsCmd id) -- operator
532 Fixity -- Renamer adds fixity; bottom until then
533 (HsCmd id) -- right operand
535 | HsPar (HsCmd id) -- parenthesised command
538 [Match id] -- bodies are HsCmd's
541 | HsIf (HsExpr id) -- predicate
542 (HsCmd id) -- then part
543 (HsCmd id) -- else part
546 | HsLet (HsBinds id) -- let(rec)
549 | HsDo (HsStmtContext Name) -- The parameterisation is unimportant
550 -- because in this context we never use
551 -- the PatGuard or ParStmt variant
552 [Stmt id] -- HsExpr's are really HsCmd's
554 PostTcType -- Type of the whole expression
557 Top-level command, introducing a new arrow.
558 This may occur inside a proc (where the stack is empty) or as an
559 argument of a command-forming operator.
563 = HsCmdTop (HsCmd id)
564 [PostTcType] -- types of inputs on the command's stack
565 PostTcType -- return type of the command
567 -- after type checking:
568 -- names used in the command's desugaring
571 %************************************************************************
573 \subsection{Record binds}
575 %************************************************************************
578 type HsRecordBinds id = [(id, HsExpr id)]
580 recBindFields :: HsRecordBinds id -> [id]
581 recBindFields rbinds = [field | (field,_) <- rbinds]
583 pp_rbinds :: OutputableBndr id => SDoc -> HsRecordBinds id -> SDoc
585 pp_rbinds thing rbinds
587 4 (braces (sep (punctuate comma (map (pp_rbind) rbinds))))
589 pp_rbind (v, e) = hsep [pprBndr LetBind v, char '=', ppr e]
594 %************************************************************************
596 \subsection{@Match@, @GRHSs@, and @GRHS@ datatypes}
598 %************************************************************************
600 @Match@es are sets of pattern bindings and right hand sides for
601 functions, patterns or case branches. For example, if a function @g@
607 then \tr{g} has two @Match@es: @(x,y) = y@ and @((x:ys),y) = y+1@.
609 It is always the case that each element of an @[Match]@ list has the
610 same number of @pats@s inside it. This corresponds to saying that
611 a function defined by pattern matching must have the same number of
612 patterns in each equation.
617 [Pat id] -- The patterns
618 (Maybe (HsType id)) -- A type signature for the result of the match
619 -- Nothing after typechecking
623 -- GRHSs are used both for pattern bindings and for Matches
625 = GRHSs [GRHS id] -- Guarded RHSs
626 (HsBinds id) -- The where clause
627 PostTcType -- Type of RHS (after type checking)
630 = GRHS [Stmt id] -- The RHS is the final ResultStmt
634 @getMatchLoc@ takes a @Match@ and returns the
635 source-location gotten from the GRHS inside.
636 THis is something of a nuisance, but no more.
639 getMatchLoc :: Match id -> SrcLoc
640 getMatchLoc (Match _ _ (GRHSs (GRHS _ loc : _) _ _)) = loc
643 We know the list must have at least one @Match@ in it.
646 pprMatches :: (OutputableBndr id) => HsMatchContext id -> [Match id] -> SDoc
647 pprMatches ctxt matches = vcat (map (pprMatch ctxt) matches)
649 -- Exported to HsBinds, which can't see the defn of HsMatchContext
650 pprFunBind :: (OutputableBndr id) => id -> [Match id] -> SDoc
651 pprFunBind fun matches = pprMatches (FunRhs fun) matches
653 -- Exported to HsBinds, which can't see the defn of HsMatchContext
654 pprPatBind :: (OutputableBndr id)
655 => Pat id -> GRHSs id -> SDoc
656 pprPatBind pat grhss = sep [ppr pat, nest 4 (pprGRHSs PatBindRhs grhss)]
659 pprMatch :: OutputableBndr id => HsMatchContext id -> Match id -> SDoc
660 pprMatch ctxt (Match pats maybe_ty grhss)
661 = pp_name ctxt <+> sep [sep (map ppr pats),
663 nest 2 (pprGRHSs ctxt grhss)]
665 pp_name (FunRhs fun) = ppr fun -- Not pprBndr; the AbsBinds will
666 -- have printed the signature
667 pp_name LambdaExpr = char '\\'
668 pp_name other = empty
670 ppr_maybe_ty = case maybe_ty of
671 Just ty -> dcolon <+> ppr ty
675 pprGRHSs :: OutputableBndr id => HsMatchContext id -> GRHSs id -> SDoc
676 pprGRHSs ctxt (GRHSs grhss binds ty)
677 = vcat (map (pprGRHS ctxt) grhss)
679 (if nullBinds binds then empty
680 else text "where" $$ nest 4 (pprDeeper (ppr binds)))
683 pprGRHS :: OutputableBndr id => HsMatchContext id -> GRHS id -> SDoc
685 pprGRHS ctxt (GRHS [ResultStmt expr _] locn)
688 pprGRHS ctxt (GRHS guarded locn)
689 = sep [char '|' <+> interpp'SP guards, pp_rhs ctxt expr]
691 ResultStmt expr _ = last guarded -- Last stmt should be a ResultStmt for guards
692 guards = init guarded
694 pp_rhs ctxt rhs = matchSeparator ctxt <+> pprDeeper (ppr rhs)
699 %************************************************************************
701 \subsection{Do stmts and list comprehensions}
703 %************************************************************************
707 = BindStmt (Pat id) (HsExpr id) SrcLoc
708 | LetStmt (HsBinds id)
709 | ResultStmt (HsExpr id) SrcLoc -- See notes that follow
710 | ExprStmt (HsExpr id) PostTcType SrcLoc -- See notes that follow
711 -- The type is the *element type* of the expression
713 -- ParStmts only occur in a list comprehension
714 | ParStmt [([Stmt id], [id])] -- After remaing, the ids are the binders
715 -- bound by the stmts and used subsequently
717 -- Recursive statement
719 --- The next two fields are only valid after renaming
720 [id] -- The ids are a subset of the variables bound by the stmts
721 -- that are used in stmts that follow the RecStmt
723 [id] -- Ditto, but these variables are the "recursive" ones, that
724 -- are used before they are bound in the stmts of the RecStmt
725 -- From a type-checking point of view, these ones have to be monomorphic
727 --- This field is only valid after typechecking
728 [HsExpr id] -- These expressions correspond
729 -- 1-to-1 with the "recursive" [id], and are the expresions that
730 -- should be returned by the recursion. They may not quite be the
731 -- Ids themselves, because the Id may be *polymorphic*, but
732 -- the returned thing has to be *monomorphic*.
735 ExprStmts and ResultStmts are a bit tricky, because what they mean
736 depends on the context. Consider the following contexts:
738 A do expression of type (m res_ty)
739 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
740 * ExprStmt E any_ty: do { ....; E; ... }
742 Translation: E >> ...
744 * ResultStmt E: do { ....; E }
748 A list comprehensions of type [elt_ty]
749 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
750 * ExprStmt E Bool: [ .. | .... E ]
752 [ .. | .... | ..., E | ... ]
754 Translation: if E then fail else ...
756 * ResultStmt E: [ E | ... ]
758 Translation: return E
760 A guard list, guarding a RHS of type rhs_ty
761 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
762 * ExprStmt E Bool: f x | ..., E, ... = ...rhs...
764 Translation: if E then fail else ...
766 * ResultStmt E: f x | ...guards... = E
770 Array comprehensions are handled like list comprehensions -=chak
773 consLetStmt :: HsBinds id -> [Stmt id] -> [Stmt id]
774 consLetStmt EmptyBinds stmts = stmts
775 consLetStmt binds stmts = LetStmt binds : stmts
779 instance OutputableBndr id => Outputable (Stmt id) where
780 ppr stmt = pprStmt stmt
782 pprStmt (BindStmt pat expr _) = hsep [ppr pat, ptext SLIT("<-"), ppr expr]
783 pprStmt (LetStmt binds) = hsep [ptext SLIT("let"), pprBinds binds]
784 pprStmt (ExprStmt expr _ _) = ppr expr
785 pprStmt (ResultStmt expr _) = ppr expr
786 pprStmt (ParStmt stmtss) = hsep (map (\stmts -> ptext SLIT("| ") <> ppr stmts) stmtss)
787 pprStmt (RecStmt segment _ _ _) = ptext SLIT("rec") <+> braces (vcat (map ppr segment))
789 pprDo :: OutputableBndr id => HsStmtContext any -> [Stmt id] -> SDoc
790 pprDo DoExpr stmts = hang (ptext SLIT("do")) 2 (vcat (map ppr stmts))
791 pprDo MDoExpr stmts = hang (ptext SLIT("mdo")) 3 (vcat (map ppr stmts))
792 pprDo ListComp stmts = pprComp brackets stmts
793 pprDo PArrComp stmts = pprComp pa_brackets stmts
795 pprComp :: OutputableBndr id => (SDoc -> SDoc) -> [Stmt id] -> SDoc
796 pprComp brack stmts = brack $
797 hang (pprExpr expr <+> char '|')
800 ResultStmt expr _ = last stmts -- Last stmt should
801 quals = init stmts -- be an ResultStmt
804 %************************************************************************
806 Template Haskell quotation brackets
808 %************************************************************************
811 data HsBracket id = ExpBr (HsExpr id) -- [| expr |]
812 | PatBr (Pat id) -- [p| pat |]
813 | DecBr (HsGroup id) -- [d| decls |]
814 | TypBr (HsType id) -- [t| type |]
815 | VarBr id -- 'x, ''T
817 instance OutputableBndr id => Outputable (HsBracket id) where
821 pprHsBracket (ExpBr e) = thBrackets empty (ppr e)
822 pprHsBracket (PatBr p) = thBrackets (char 'p') (ppr p)
823 pprHsBracket (DecBr d) = thBrackets (char 'd') (ppr d)
824 pprHsBracket (TypBr t) = thBrackets (char 't') (ppr t)
825 pprHsBracket (VarBr n) = char '\'' <> ppr n
826 -- Infelicity: can't show ' vs '', because
827 -- we can't ask n what its OccName is, because the
828 -- pretty-printer for HsExpr doesn't ask for NamedThings
829 -- But the pretty-printer for names will show the OccName class
831 thBrackets pp_kind pp_body = char '[' <> pp_kind <> char '|' <+>
832 pp_body <+> ptext SLIT("|]")
835 %************************************************************************
837 \subsection{Enumerations and list comprehensions}
839 %************************************************************************
844 | FromThen (HsExpr id)
848 | FromThenTo (HsExpr id)
854 instance OutputableBndr id => Outputable (ArithSeqInfo id) where
855 ppr (From e1) = hcat [ppr e1, pp_dotdot]
856 ppr (FromThen e1 e2) = hcat [ppr e1, comma, space, ppr e2, pp_dotdot]
857 ppr (FromTo e1 e3) = hcat [ppr e1, pp_dotdot, ppr e3]
858 ppr (FromThenTo e1 e2 e3)
859 = hcat [ppr e1, comma, space, ppr e2, pp_dotdot, ppr e3]
861 pp_dotdot = ptext SLIT(" .. ")
865 %************************************************************************
867 \subsection{HsMatchCtxt}
869 %************************************************************************
872 data HsMatchContext id -- Context of a Match
873 = FunRhs id -- Function binding for f
874 | CaseAlt -- Guard on a case alternative
875 | LambdaExpr -- Pattern of a lambda
876 | ProcExpr -- Pattern of a proc
877 | PatBindRhs -- Pattern binding
878 | RecUpd -- Record update [used only in DsExpr to tell matchWrapper
879 -- what sort of runtime error message to generate]
880 | StmtCtxt (HsStmtContext id) -- Pattern of a do-stmt or list comprehension
883 data HsStmtContext id
886 | MDoExpr -- Recursive do-expression
887 | PArrComp -- Parallel array comprehension
888 | PatGuard (HsMatchContext id) -- Pattern guard for specified thing
889 | ParStmtCtxt (HsStmtContext id) -- A branch of a parallel stmt
893 isDoExpr :: HsStmtContext id -> Bool
894 isDoExpr DoExpr = True
895 isDoExpr MDoExpr = True
896 isDoExpr other = False
900 matchSeparator (FunRhs _) = ptext SLIT("=")
901 matchSeparator CaseAlt = ptext SLIT("->")
902 matchSeparator LambdaExpr = ptext SLIT("->")
903 matchSeparator ProcExpr = ptext SLIT("->")
904 matchSeparator PatBindRhs = ptext SLIT("=")
905 matchSeparator (StmtCtxt _) = ptext SLIT("<-")
906 matchSeparator RecUpd = panic "unused"
910 pprMatchContext (FunRhs fun) = ptext SLIT("the definition of") <+> quotes (ppr fun)
911 pprMatchContext CaseAlt = ptext SLIT("a case alternative")
912 pprMatchContext RecUpd = ptext SLIT("a record-update construct")
913 pprMatchContext PatBindRhs = ptext SLIT("a pattern binding")
914 pprMatchContext LambdaExpr = ptext SLIT("a lambda abstraction")
915 pprMatchContext ProcExpr = ptext SLIT("an arrow abstraction")
916 pprMatchContext (StmtCtxt ctxt) = ptext SLIT("a pattern binding in") $$ pprStmtContext ctxt
918 pprMatchRhsContext (FunRhs fun) = ptext SLIT("a right-hand side of function") <+> quotes (ppr fun)
919 pprMatchRhsContext CaseAlt = ptext SLIT("the body of a case alternative")
920 pprMatchRhsContext PatBindRhs = ptext SLIT("the right-hand side of a pattern binding")
921 pprMatchRhsContext LambdaExpr = ptext SLIT("the body of a lambda")
922 pprMatchRhsContext ProcExpr = ptext SLIT("the body of a proc")
923 pprMatchRhsContext RecUpd = panic "pprMatchRhsContext"
925 pprStmtContext (ParStmtCtxt c) = sep [ptext SLIT("a parallel branch of"), pprStmtContext c]
926 pprStmtContext (PatGuard ctxt) = ptext SLIT("a pattern guard for") $$ pprMatchContext ctxt
927 pprStmtContext DoExpr = ptext SLIT("a 'do' expression")
928 pprStmtContext MDoExpr = ptext SLIT("an 'mdo' expression")
929 pprStmtContext ListComp = ptext SLIT("a list comprehension")
930 pprStmtContext PArrComp = ptext SLIT("an array comprehension")
932 -- Used for the result statement of comprehension
933 -- e.g. the 'e' in [ e | ... ]
934 -- or the 'r' in f x = r
935 pprStmtResultContext (PatGuard ctxt) = pprMatchRhsContext ctxt
936 pprStmtResultContext other = ptext SLIT("the result of") <+> pprStmtContext other
939 -- Used to generate the string for a *runtime* error message
940 matchContextErrString (FunRhs fun) = "function " ++ showSDoc (ppr fun)
941 matchContextErrString CaseAlt = "case"
942 matchContextErrString PatBindRhs = "pattern binding"
943 matchContextErrString RecUpd = "record update"
944 matchContextErrString LambdaExpr = "lambda"
945 matchContextErrString ProcExpr = "proc"
946 matchContextErrString (StmtCtxt (ParStmtCtxt c)) = matchContextErrString (StmtCtxt c)
947 matchContextErrString (StmtCtxt (PatGuard _)) = "pattern guard"
948 matchContextErrString (StmtCtxt DoExpr) = "'do' expression"
949 matchContextErrString (StmtCtxt MDoExpr) = "'mdo' expression"
950 matchContextErrString (StmtCtxt ListComp) = "list comprehension"
951 matchContextErrString (StmtCtxt PArrComp) = "array comprehension"