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 )
15 import HsLit ( HsLit, HsOverLit )
16 import HsTypes ( HsType, PostTcType, SyntaxName )
17 import HsImpExp ( isOperator, pprHsVar )
20 import ForeignCall ( Safety )
21 import PprType ( pprParendType )
23 import Var ( TyVar, Id )
25 import NameSet ( FreeVars )
26 import DataCon ( DataCon )
27 import CStrings ( CLabelString, pprCLabelString )
28 import BasicTypes ( IPName, Boxity, tupleParens, Fixity(..) )
29 import SrcLoc ( SrcLoc )
34 %************************************************************************
36 \subsection{Expressions proper}
38 %************************************************************************
42 = HsVar id -- variable
43 | HsIPVar (IPName id) -- implicit parameter
44 | HsOverLit HsOverLit -- Overloaded literals; eliminated by type checker
45 | HsLit HsLit -- Simple (non-overloaded) literals
47 | HsLam (Match id) -- lambda
48 | HsApp (HsExpr id) -- application
51 -- Operator applications:
52 -- NB Bracketed ops such as (+) come out as Vars.
54 -- NB We need an expr for the operator in an OpApp/Section since
55 -- the typechecker may need to apply the operator to a few types.
57 | OpApp (HsExpr id) -- left operand
58 (HsExpr id) -- operator
59 Fixity -- Renamer adds fixity; bottom until then
60 (HsExpr id) -- right operand
62 -- We preserve prefix negation and parenthesis for the precedence parser.
63 -- They are eventually removed by the type checker.
65 | NegApp (HsExpr id) -- negated expr
66 SyntaxName -- Name of 'negate' (see RnEnv.lookupSyntaxName)
68 | HsPar (HsExpr id) -- parenthesised expr
70 | SectionL (HsExpr id) -- operand
71 (HsExpr id) -- operator
72 | SectionR (HsExpr id) -- operator
73 (HsExpr id) -- operand
79 | HsIf (HsExpr id) -- predicate
80 (HsExpr id) -- then part
81 (HsExpr id) -- else part
84 | HsLet (HsBinds id) -- let(rec)
87 | HsDo (HsStmtContext Name) -- The parameterisation is unimportant
88 -- because in this context we never use
89 -- the PatGuard or ParStmt variant
90 [Stmt id] -- "do":one or more stmts
91 (ReboundNames id) -- Ids for [return,fail,>>=,>>]
92 PostTcType -- Type of the whole expression
95 | ExplicitList -- syntactic list
96 PostTcType -- Gives type of components of list
99 | ExplicitPArr -- syntactic parallel array: [:e1, ..., en:]
100 PostTcType -- type of elements of the parallel array
103 | ExplicitTuple -- tuple
105 -- NB: Unit is ExplicitTuple []
106 -- for tuples, we can get the types
107 -- direct from the components
111 -- Record construction
112 | RecordCon id -- The constructor
115 | RecordConOut DataCon
116 (HsExpr id) -- Data con Id applied to type args
121 | RecordUpd (HsExpr id)
124 | RecordUpdOut (HsExpr id) -- TRANSLATION
125 Type -- Type of *input* record
126 Type -- Type of *result* record (may differ from
127 -- type of input record)
130 | ExprWithTySig -- signature binding
133 | ArithSeqIn -- arithmetic sequence
136 (HsExpr id) -- (typechecked, of course)
138 | PArrSeqIn -- arith. sequence for parallel array
139 (ArithSeqInfo id) -- [:e1..e2:] or [:e1, e2..e3:]
141 (HsExpr id) -- (typechecked, of course)
144 | HsCCall CLabelString -- call into the C world; string is
145 [HsExpr id] -- the C function; exprs are the
146 -- arguments to pass.
147 Safety -- True <=> might cause Haskell
148 -- garbage-collection (must generate
149 -- more paranoid code)
150 Bool -- True <=> it's really a "casm"
151 -- NOTE: this CCall is the *boxed*
152 -- version; the desugarer will convert
153 -- it into the unboxed "ccall#".
154 PostTcType -- The result type; will be *bottom*
155 -- until the typechecker gets ahold of it
157 | HsSCC FastString -- "set cost centre" (_scc_) annotation
158 (HsExpr id) -- expr whose cost is to be measured
160 | HsCoreAnn FastString -- hdaume: core annotation
163 -----------------------------------------------------------
164 -- MetaHaskell Extensions
165 | HsBracket (HsBracket id) SrcLoc
167 | HsBracketOut (HsBracket Name) -- Output of the type checker is the *original*
168 [PendingSplice] -- renamed expression, plus *typechecked* splices
169 -- to be pasted back in by the desugarer
171 | HsSplice id (HsExpr id) SrcLoc -- $z or $(f 4)
172 -- The id is just a unique name to
173 -- identify this splice point
175 | HsReify (HsReify id) -- reifyType t, reifyDecl i, reifyFixity
177 -----------------------------------------------------------
178 -- Arrow notation extension
180 | HsProc (Pat id) -- arrow abstraction, proc
181 (HsCmdTop id) -- body of the abstraction
182 -- always has an empty stack
185 ---------------------------------------
186 -- The following are commands, not expressions proper
188 | HsArrApp -- Arrow tail, or arrow application (f -< arg)
189 (HsExpr id) -- arrow expression, f
190 (HsExpr id) -- input expression, arg
191 PostTcType -- type of the arrow expressions f,
192 -- of the form a t t', where arg :: t
193 HsArrAppType -- higher-order (-<<) or first-order (-<)
194 Bool -- True => right-to-left (f -< arg)
195 -- False => left-to-right (arg >- f)
198 | HsArrForm -- Command formation, (| e cmd1 .. cmdn |)
199 (HsExpr id) -- the operator
200 -- after type-checking, a type abstraction to be
201 -- applied to the type of the local environment tuple
202 (Maybe Fixity) -- fixity (filled in by the renamer), for forms that
203 -- were converted from OpApp's by the renamer
204 [HsCmdTop id] -- argument commands
210 These constructors only appear temporarily in the parser.
211 The renamer translates them into the Right Thing.
214 | EWildPat -- wildcard
216 | EAsPat id -- as pattern
219 | ELazyPat (HsExpr id) -- ~ pattern
221 | HsType (HsType id) -- Explicit type argument; e.g f {| Int |} x y
224 Everything from here on appears only in typechecker output.
227 | TyLam -- TRANSLATION
230 | TyApp -- TRANSLATION
231 (HsExpr id) -- generated by Spec
234 -- DictLam and DictApp are "inverses"
242 type PendingSplice = (Name, HsExpr Id) -- Typechecked splices, waiting to be
243 -- pasted back in by the desugarer
246 Table of bindings of names used in rebindable syntax.
247 This gets filled in by the renamer.
250 type ReboundNames id = [(Name, HsExpr id)]
251 -- * Before the renamer, this list is empty
253 -- * After the renamer, it takes the form [(std_name, HsVar actual_name)]
254 -- For example, for the 'return' op of a monad
255 -- normal case: (GHC.Base.return, HsVar GHC.Base.return)
256 -- with rebindable syntax: (GHC.Base.return, return_22)
257 -- where return_22 is whatever "return" is in scope
259 -- * After the type checker, it takes the form [(std_name, <expression>)]
260 -- where <expression> is the evidence for the method
263 A @Dictionary@, unless of length 0 or 1, becomes a tuple. A
264 @ClassDictLam dictvars methods expr@ is, therefore:
266 \ x -> case x of ( dictvars-and-methods-tuple ) -> expr
270 instance OutputableBndr id => Outputable (HsExpr id) where
271 ppr expr = pprExpr expr
275 pprExpr :: OutputableBndr id => HsExpr id -> SDoc
277 pprExpr e = pprDeeper (ppr_expr e)
278 pprBinds b = pprDeeper (ppr b)
280 ppr_expr (HsVar v) = pprHsVar v
281 ppr_expr (HsIPVar v) = ppr v
282 ppr_expr (HsLit lit) = ppr lit
283 ppr_expr (HsOverLit lit) = ppr lit
285 ppr_expr (HsLam match) = pprMatch LambdaExpr match
287 ppr_expr expr@(HsApp e1 e2)
288 = let (fun, args) = collect_args expr [] in
289 (ppr_expr fun) <+> (sep (map ppr_expr args))
291 collect_args (HsApp fun arg) args = collect_args fun (arg:args)
292 collect_args fun args = (fun, args)
294 ppr_expr (OpApp e1 op fixity e2)
296 HsVar v -> pp_infixly v
299 pp_e1 = pprParendExpr e1 -- Add parens to make precedence clear
300 pp_e2 = pprParendExpr e2
303 = hang (pprExpr op) 4 (sep [pp_e1, pp_e2])
306 = sep [pp_e1, hsep [pprInfix v, pp_e2]]
308 ppr_expr (NegApp e _) = char '-' <+> pprParendExpr e
310 ppr_expr (HsPar e) = parens (ppr_expr e)
312 ppr_expr (SectionL expr op)
314 HsVar v -> pp_infixly v
317 pp_expr = pprParendExpr expr
319 pp_prefixly = hang (hsep [text " \\ x_ ->", ppr op])
320 4 (hsep [pp_expr, ptext SLIT("x_ )")])
321 pp_infixly v = parens (sep [pp_expr, ppr v])
323 ppr_expr (SectionR op expr)
325 HsVar v -> pp_infixly v
328 pp_expr = pprParendExpr expr
330 pp_prefixly = hang (hsep [text "( \\ x_ ->", ppr op, ptext SLIT("x_")])
331 4 ((<>) pp_expr rparen)
333 = parens (sep [ppr v, pp_expr])
335 ppr_expr (HsCase expr matches _)
336 = sep [ sep [ptext SLIT("case"), nest 4 (pprExpr expr), ptext SLIT("of")],
337 nest 2 (pprMatches CaseAlt matches) ]
339 ppr_expr (HsIf e1 e2 e3 _)
340 = sep [hsep [ptext SLIT("if"), nest 2 (pprExpr e1), ptext SLIT("then")],
345 -- special case: let ... in let ...
346 ppr_expr (HsLet binds expr@(HsLet _ _))
347 = sep [hang (ptext SLIT("let")) 2 (hsep [pprBinds binds, ptext SLIT("in")]),
350 ppr_expr (HsLet binds expr)
351 = sep [hang (ptext SLIT("let")) 2 (pprBinds binds),
352 hang (ptext SLIT("in")) 2 (ppr expr)]
354 ppr_expr (HsDo do_or_list_comp stmts _ _ _) = pprDo do_or_list_comp stmts
356 ppr_expr (ExplicitList _ exprs)
357 = brackets (fsep (punctuate comma (map ppr_expr exprs)))
359 ppr_expr (ExplicitPArr _ exprs)
360 = pa_brackets (fsep (punctuate comma (map ppr_expr exprs)))
362 ppr_expr (ExplicitTuple exprs boxity)
363 = tupleParens boxity (sep (punctuate comma (map ppr_expr exprs)))
365 ppr_expr (RecordCon con_id rbinds)
366 = pp_rbinds (ppr con_id) rbinds
367 ppr_expr (RecordConOut data_con con rbinds)
368 = pp_rbinds (ppr con) rbinds
370 ppr_expr (RecordUpd aexp rbinds)
371 = pp_rbinds (pprParendExpr aexp) rbinds
372 ppr_expr (RecordUpdOut aexp _ _ rbinds)
373 = pp_rbinds (pprParendExpr aexp) rbinds
375 ppr_expr (ExprWithTySig expr sig)
376 = hang (nest 2 (ppr_expr expr) <+> dcolon)
379 ppr_expr (ArithSeqIn info)
380 = brackets (ppr info)
381 ppr_expr (ArithSeqOut expr info)
382 = brackets (ppr info)
384 ppr_expr (PArrSeqIn info)
385 = pa_brackets (ppr info)
386 ppr_expr (PArrSeqOut expr info)
387 = pa_brackets (ppr info)
389 ppr_expr EWildPat = char '_'
390 ppr_expr (ELazyPat e) = char '~' <> pprParendExpr e
391 ppr_expr (EAsPat v e) = ppr v <> char '@' <> pprParendExpr e
393 ppr_expr (HsCCall fun args _ is_asm result_ty)
395 then ptext SLIT("_casm_ ``") <> pprCLabelString fun <> ptext SLIT("''")
396 else ptext SLIT("_ccall_") <+> pprCLabelString fun)
397 4 (sep (map pprParendExpr args))
399 ppr_expr (HsSCC lbl expr)
400 = sep [ ptext SLIT("_scc_") <+> doubleQuotes (ftext lbl), pprParendExpr expr ]
402 ppr_expr (TyLam tyvars expr)
403 = hang (hsep [ptext SLIT("/\\"),
404 hsep (map (pprBndr LambdaBind) tyvars),
408 ppr_expr (TyApp expr [ty])
409 = hang (ppr_expr expr) 4 (pprParendType ty)
411 ppr_expr (TyApp expr tys)
412 = hang (ppr_expr expr)
413 4 (brackets (interpp'SP tys))
415 ppr_expr (DictLam dictvars expr)
416 = hang (hsep [ptext SLIT("\\{-dict-}"),
417 hsep (map (pprBndr LambdaBind) dictvars),
421 ppr_expr (DictApp expr [dname])
422 = hang (ppr_expr expr) 4 (ppr dname)
424 ppr_expr (DictApp expr dnames)
425 = hang (ppr_expr expr)
426 4 (brackets (interpp'SP dnames))
428 ppr_expr (HsType id) = ppr id
430 ppr_expr (HsSplice n e _) = char '$' <> brackets (ppr n) <> pprParendExpr e
431 ppr_expr (HsBracket b _) = pprHsBracket b
432 ppr_expr (HsBracketOut e ps) = ppr e $$ ptext SLIT("where") <+> ppr ps
433 ppr_expr (HsReify r) = ppr r
435 ppr_expr (HsProc pat (HsCmdTop cmd _ _ _) _)
436 = hsep [ptext SLIT("proc"), ppr pat, ptext SLIT("->"), pprExpr cmd]
438 ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp True _)
439 = hsep [pprExpr arrow, ptext SLIT("-<"), pprExpr arg]
440 ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp False _)
441 = hsep [pprExpr arg, ptext SLIT(">-"), pprExpr arrow]
442 ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp True _)
443 = hsep [pprExpr arrow, ptext SLIT("-<<"), pprExpr arg]
444 ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp False _)
445 = hsep [pprExpr arg, ptext SLIT(">>-"), pprExpr arrow]
447 ppr_expr (HsArrForm (HsVar v) (Just _) [arg1, arg2] _)
448 = sep [pprCmdArg arg1, hsep [pprInfix v, pprCmdArg arg2]]
449 ppr_expr (HsArrForm op _ args _)
450 = hang (ptext SLIT("(|") <> pprExpr op)
451 4 (sep (map pprCmdArg args) <> ptext SLIT("|)"))
453 pprCmdArg :: OutputableBndr id => HsCmdTop id -> SDoc
454 pprCmdArg (HsCmdTop cmd@(HsArrForm _ Nothing [] _) _ _ _) = pprExpr cmd
455 pprCmdArg (HsCmdTop cmd _ _ _) = parens (pprExpr cmd)
457 -- Put a var in backquotes if it's not an operator already
458 pprInfix :: Outputable name => name -> SDoc
459 pprInfix v | isOperator ppr_v = ppr_v
460 | otherwise = char '`' <> ppr_v <> char '`'
464 -- add parallel array brackets around a document
466 pa_brackets :: SDoc -> SDoc
467 pa_brackets p = ptext SLIT("[:") <> p <> ptext SLIT(":]")
470 Parenthesize unless very simple:
472 pprParendExpr :: OutputableBndr id => HsExpr id -> SDoc
476 pp_as_was = pprExpr expr
483 HsIPVar _ -> pp_as_was
484 ExplicitList _ _ -> pp_as_was
485 ExplicitPArr _ _ -> pp_as_was
486 ExplicitTuple _ _ -> pp_as_was
489 _ -> parens pp_as_was
492 %************************************************************************
494 \subsection{Commands (in arrow abstractions)}
496 %************************************************************************
498 We re-use HsExpr to represent these.
501 type HsCmd id = HsExpr id
503 data HsArrAppType = HsHigherOrderApp | HsFirstOrderApp
506 The legal constructors for commands are:
508 = HsArrApp ... -- as above
510 | HsArrForm ... -- as above
515 | HsLam (Match id) -- kappa
517 -- the renamer turns this one into HsArrForm
518 | OpApp (HsExpr id) -- left operand
519 (HsCmd id) -- operator
520 Fixity -- Renamer adds fixity; bottom until then
521 (HsCmd id) -- right operand
523 | HsPar (HsCmd id) -- parenthesised command
526 [Match id] -- bodies are HsCmd's
529 | HsIf (HsExpr id) -- predicate
530 (HsCmd id) -- then part
531 (HsCmd id) -- else part
534 | HsLet (HsBinds id) -- let(rec)
537 | HsDo (HsStmtContext Name) -- The parameterisation is unimportant
538 -- because in this context we never use
539 -- the PatGuard or ParStmt variant
540 [Stmt id] -- HsExpr's are really HsCmd's
542 PostTcType -- Type of the whole expression
545 Top-level command, introducing a new arrow.
546 This may occur inside a proc (where the stack is empty) or as an
547 argument of a command-forming operator.
551 = HsCmdTop (HsCmd id)
552 [PostTcType] -- types of inputs on the command's stack
553 PostTcType -- return type of the command
555 -- after type checking:
556 -- names used in the command's desugaring
559 %************************************************************************
561 \subsection{Record binds}
563 %************************************************************************
566 type HsRecordBinds id = [(id, HsExpr id)]
568 recBindFields :: HsRecordBinds id -> [id]
569 recBindFields rbinds = [field | (field,_) <- rbinds]
571 pp_rbinds :: OutputableBndr id => SDoc -> HsRecordBinds id -> SDoc
573 pp_rbinds thing rbinds
575 4 (braces (sep (punctuate comma (map (pp_rbind) rbinds))))
577 pp_rbind (v, e) = hsep [pprBndr LetBind v, char '=', ppr e]
582 %************************************************************************
584 \subsection{@Match@, @GRHSs@, and @GRHS@ datatypes}
586 %************************************************************************
588 @Match@es are sets of pattern bindings and right hand sides for
589 functions, patterns or case branches. For example, if a function @g@
595 then \tr{g} has two @Match@es: @(x,y) = y@ and @((x:ys),y) = y+1@.
597 It is always the case that each element of an @[Match]@ list has the
598 same number of @pats@s inside it. This corresponds to saying that
599 a function defined by pattern matching must have the same number of
600 patterns in each equation.
605 [Pat id] -- The patterns
606 (Maybe (HsType id)) -- A type signature for the result of the match
607 -- Nothing after typechecking
611 -- GRHSs are used both for pattern bindings and for Matches
613 = GRHSs [GRHS id] -- Guarded RHSs
614 (HsBinds id) -- The where clause
615 PostTcType -- Type of RHS (after type checking)
618 = GRHS [Stmt id] -- The RHS is the final ResultStmt
621 mkSimpleMatch :: [Pat id] -> HsExpr id -> Type -> SrcLoc -> Match id
622 mkSimpleMatch pats rhs rhs_ty locn
623 = Match pats Nothing (GRHSs (unguardedRHS rhs locn) EmptyBinds rhs_ty)
625 unguardedRHS :: HsExpr id -> SrcLoc -> [GRHS id]
626 unguardedRHS rhs loc = [GRHS [ResultStmt rhs loc] loc]
628 glueBindsOnGRHSs :: HsBinds id -> GRHSs id -> GRHSs id
629 glueBindsOnGRHSs EmptyBinds grhss = grhss
630 glueBindsOnGRHSs binds1 (GRHSs grhss binds2 ty)
631 = GRHSs grhss (binds1 `ThenBinds` binds2) ty
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)
816 instance OutputableBndr id => Outputable (HsBracket id) where
820 pprHsBracket (ExpBr e) = thBrackets empty (ppr e)
821 pprHsBracket (PatBr p) = thBrackets (char 'p') (ppr p)
822 pprHsBracket (DecBr d) = thBrackets (char 'd') (ppr d)
823 pprHsBracket (TypBr t) = thBrackets (char 't') (ppr t)
826 thBrackets pp_kind pp_body = char '[' <> pp_kind <> char '|' <+>
827 pp_body <+> ptext SLIT("|]")
829 data HsReify id = Reify ReifyFlavour id -- Pre typechecking
830 | ReifyOut ReifyFlavour Name -- Post typechecking
831 -- The Name could be the name of
832 -- an Id, TyCon, or Class
834 data ReifyFlavour = ReifyDecl | ReifyType | ReifyFixity
836 instance Outputable id => Outputable (HsReify id) where
837 ppr (Reify flavour id) = ppr flavour <+> ppr id
838 ppr (ReifyOut flavour thing) = ppr flavour <+> ppr thing
840 instance Outputable ReifyFlavour where
841 ppr ReifyDecl = ptext SLIT("reifyDecl")
842 ppr ReifyType = ptext SLIT("reifyType")
843 ppr ReifyFixity = ptext SLIT("reifyFixity")
846 %************************************************************************
848 \subsection{Enumerations and list comprehensions}
850 %************************************************************************
855 | FromThen (HsExpr id)
859 | FromThenTo (HsExpr id)
865 instance OutputableBndr id => Outputable (ArithSeqInfo id) where
866 ppr (From e1) = hcat [ppr e1, pp_dotdot]
867 ppr (FromThen e1 e2) = hcat [ppr e1, comma, space, ppr e2, pp_dotdot]
868 ppr (FromTo e1 e3) = hcat [ppr e1, pp_dotdot, ppr e3]
869 ppr (FromThenTo e1 e2 e3)
870 = hcat [ppr e1, comma, space, ppr e2, pp_dotdot, ppr e3]
872 pp_dotdot = ptext SLIT(" .. ")
876 %************************************************************************
878 \subsection{HsMatchCtxt}
880 %************************************************************************
883 data HsMatchContext id -- Context of a Match
884 = FunRhs id -- Function binding for f
885 | CaseAlt -- Guard on a case alternative
886 | LambdaExpr -- Pattern of a lambda
887 | ProcExpr -- Pattern of a proc
888 | PatBindRhs -- Pattern binding
889 | RecUpd -- Record update [used only in DsExpr to tell matchWrapper
890 -- what sort of runtime error message to generate]
891 | StmtCtxt (HsStmtContext id) -- Pattern of a do-stmt or list comprehension
894 data HsStmtContext id
897 | MDoExpr -- Recursive do-expression
898 | PArrComp -- Parallel array comprehension
899 | PatGuard (HsMatchContext id) -- Pattern guard for specified thing
900 | ParStmtCtxt (HsStmtContext id) -- A branch of a parallel stmt
904 isDoExpr :: HsStmtContext id -> Bool
905 isDoExpr DoExpr = True
906 isDoExpr MDoExpr = True
907 isDoExpr other = False
911 matchSeparator (FunRhs _) = ptext SLIT("=")
912 matchSeparator CaseAlt = ptext SLIT("->")
913 matchSeparator LambdaExpr = ptext SLIT("->")
914 matchSeparator ProcExpr = ptext SLIT("->")
915 matchSeparator PatBindRhs = ptext SLIT("=")
916 matchSeparator (StmtCtxt _) = ptext SLIT("<-")
917 matchSeparator RecUpd = panic "unused"
921 pprMatchContext (FunRhs fun) = ptext SLIT("the definition of") <+> quotes (ppr fun)
922 pprMatchContext CaseAlt = ptext SLIT("a case alternative")
923 pprMatchContext RecUpd = ptext SLIT("a record-update construct")
924 pprMatchContext PatBindRhs = ptext SLIT("a pattern binding")
925 pprMatchContext LambdaExpr = ptext SLIT("a lambda abstraction")
926 pprMatchContext ProcExpr = ptext SLIT("an arrow abstraction")
927 pprMatchContext (StmtCtxt ctxt) = ptext SLIT("a pattern binding in") $$ pprStmtContext ctxt
929 pprMatchRhsContext (FunRhs fun) = ptext SLIT("a right-hand side of function") <+> quotes (ppr fun)
930 pprMatchRhsContext CaseAlt = ptext SLIT("the body of a case alternative")
931 pprMatchRhsContext PatBindRhs = ptext SLIT("the right-hand side of a pattern binding")
932 pprMatchRhsContext LambdaExpr = ptext SLIT("the body of a lambda")
933 pprMatchRhsContext ProcExpr = ptext SLIT("the body of a proc")
934 pprMatchRhsContext RecUpd = panic "pprMatchRhsContext"
936 pprStmtContext (ParStmtCtxt c) = sep [ptext SLIT("a parallel branch of"), pprStmtContext c]
937 pprStmtContext (PatGuard ctxt) = ptext SLIT("a pattern guard for") $$ pprMatchContext ctxt
938 pprStmtContext DoExpr = ptext SLIT("a 'do' expression")
939 pprStmtContext MDoExpr = ptext SLIT("an 'mdo' expression")
940 pprStmtContext ListComp = ptext SLIT("a list comprehension")
941 pprStmtContext PArrComp = ptext SLIT("an array comprehension")
943 -- Used for the result statement of comprehension
944 -- e.g. the 'e' in [ e | ... ]
945 -- or the 'r' in f x = r
946 pprStmtResultContext (PatGuard ctxt) = pprMatchRhsContext ctxt
947 pprStmtResultContext other = ptext SLIT("the result of") <+> pprStmtContext other
950 -- Used to generate the string for a *runtime* error message
951 matchContextErrString (FunRhs fun) = "function " ++ showSDoc (ppr fun)
952 matchContextErrString CaseAlt = "case"
953 matchContextErrString PatBindRhs = "pattern binding"
954 matchContextErrString RecUpd = "record update"
955 matchContextErrString LambdaExpr = "lambda"
956 matchContextErrString ProcExpr = "proc"
957 matchContextErrString (StmtCtxt (ParStmtCtxt c)) = matchContextErrString (StmtCtxt c)
958 matchContextErrString (StmtCtxt (PatGuard _)) = "pattern guard"
959 matchContextErrString (StmtCtxt DoExpr) = "'do' expression"
960 matchContextErrString (StmtCtxt MDoExpr) = "'mdo' expression"
961 matchContextErrString (StmtCtxt ListComp) = "list comprehension"
962 matchContextErrString (StmtCtxt PArrComp) = "array comprehension"