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 PprType ( pprParendType )
22 import Var ( TyVar, Id )
24 import DataCon ( DataCon )
25 import BasicTypes ( IPName, Boxity, tupleParens, Fixity(..) )
26 import SrcLoc ( SrcLoc, generatedSrcLoc )
32 %************************************************************************
34 Some useful helpers for constructing expressions
36 %************************************************************************
39 mkHsApps f xs = foldl HsApp (HsVar f) xs
40 mkHsVarApps f xs = foldl HsApp (HsVar f) (map HsVar xs)
42 mkHsIntLit n = HsLit (HsInt n)
43 mkHsString s = HsString (mkFastString s)
45 mkConPat con vars = ConPatIn con (PrefixCon (map VarPat vars))
46 mkNullaryConPat con = ConPatIn con (PrefixCon [])
48 mkSimpleHsAlt :: Pat id -> HsExpr id -> Match id
49 -- A simple lambda with a single pattern, no binds, no guards; pre-typechecking
50 mkSimpleHsAlt pat expr
51 = mkSimpleMatch [pat] expr placeHolderType generatedSrcLoc
53 mkSimpleMatch :: [Pat id] -> HsExpr id -> Type -> SrcLoc -> Match id
54 mkSimpleMatch pats rhs rhs_ty locn
55 = Match pats Nothing (GRHSs (unguardedRHS rhs locn) EmptyBinds rhs_ty)
57 unguardedRHS :: HsExpr id -> SrcLoc -> [GRHS id]
58 unguardedRHS rhs loc = [GRHS [ResultStmt rhs loc] loc]
60 glueBindsOnGRHSs :: HsBinds id -> GRHSs id -> GRHSs id
61 glueBindsOnGRHSs EmptyBinds grhss = grhss
62 glueBindsOnGRHSs binds1 (GRHSs grhss binds2 ty)
63 = GRHSs grhss (binds1 `ThenBinds` binds2) ty
67 %************************************************************************
69 \subsection{Expressions proper}
71 %************************************************************************
75 = HsVar id -- variable
76 | HsIPVar (IPName id) -- implicit parameter
77 | HsOverLit HsOverLit -- Overloaded literals; eliminated by type checker
78 | HsLit HsLit -- Simple (non-overloaded) literals
80 | HsLam (Match id) -- lambda
81 | HsApp (HsExpr id) -- application
84 -- Operator applications:
85 -- NB Bracketed ops such as (+) come out as Vars.
87 -- NB We need an expr for the operator in an OpApp/Section since
88 -- the typechecker may need to apply the operator to a few types.
90 | OpApp (HsExpr id) -- left operand
91 (HsExpr id) -- operator
92 Fixity -- Renamer adds fixity; bottom until then
93 (HsExpr id) -- right operand
95 -- We preserve prefix negation and parenthesis for the precedence parser.
96 -- They are eventually removed by the type checker.
98 | NegApp (HsExpr id) -- negated expr
99 SyntaxName -- Name of 'negate' (see RnEnv.lookupSyntaxName)
101 | HsPar (HsExpr id) -- parenthesised expr
103 | SectionL (HsExpr id) -- operand
104 (HsExpr id) -- operator
105 | SectionR (HsExpr id) -- operator
106 (HsExpr id) -- operand
112 | HsIf (HsExpr id) -- predicate
113 (HsExpr id) -- then part
114 (HsExpr id) -- else part
117 | HsLet (HsBinds id) -- let(rec)
120 | HsDo (HsStmtContext Name) -- The parameterisation is unimportant
121 -- because in this context we never use
122 -- the PatGuard or ParStmt variant
123 [Stmt id] -- "do":one or more stmts
124 (ReboundNames id) -- Ids for [return,fail,>>=,>>]
125 PostTcType -- Type of the whole expression
128 | ExplicitList -- syntactic list
129 PostTcType -- Gives type of components of list
132 | ExplicitPArr -- syntactic parallel array: [:e1, ..., en:]
133 PostTcType -- type of elements of the parallel array
136 | ExplicitTuple -- tuple
138 -- NB: Unit is ExplicitTuple []
139 -- for tuples, we can get the types
140 -- direct from the components
144 -- Record construction
145 | RecordCon id -- The constructor
148 | RecordConOut DataCon
149 (HsExpr id) -- Data con Id applied to type args
154 | RecordUpd (HsExpr id)
157 | RecordUpdOut (HsExpr id) -- TRANSLATION
158 Type -- Type of *input* record
159 Type -- Type of *result* record (may differ from
160 -- type of input record)
163 | ExprWithTySig -- signature binding
166 | ArithSeqIn -- arithmetic sequence
169 (HsExpr id) -- (typechecked, of course)
171 | PArrSeqIn -- arith. sequence for parallel array
172 (ArithSeqInfo id) -- [:e1..e2:] or [:e1, e2..e3:]
174 (HsExpr id) -- (typechecked, of course)
177 | HsSCC FastString -- "set cost centre" (_scc_) annotation
178 (HsExpr id) -- expr whose cost is to be measured
180 | HsCoreAnn FastString -- hdaume: core annotation
183 -----------------------------------------------------------
184 -- MetaHaskell Extensions
185 | HsBracket (HsBracket id) SrcLoc
187 | HsBracketOut (HsBracket Name) -- Output of the type checker is the *original*
188 [PendingSplice] -- renamed expression, plus *typechecked* splices
189 -- to be pasted back in by the desugarer
191 | HsSplice id (HsExpr id) SrcLoc -- $z or $(f 4)
192 -- The id is just a unique name to
193 -- identify this splice point
195 | HsReify (HsReify id) -- reifyType t, reifyDecl i, reifyFixity
197 -----------------------------------------------------------
198 -- Arrow notation extension
200 | HsProc (Pat id) -- arrow abstraction, proc
201 (HsCmdTop id) -- body of the abstraction
202 -- always has an empty stack
205 ---------------------------------------
206 -- The following are commands, not expressions proper
208 | HsArrApp -- Arrow tail, or arrow application (f -< arg)
209 (HsExpr id) -- arrow expression, f
210 (HsExpr id) -- input expression, arg
211 PostTcType -- type of the arrow expressions f,
212 -- of the form a t t', where arg :: t
213 HsArrAppType -- higher-order (-<<) or first-order (-<)
214 Bool -- True => right-to-left (f -< arg)
215 -- False => left-to-right (arg >- f)
218 | HsArrForm -- Command formation, (| e cmd1 .. cmdn |)
219 (HsExpr id) -- the operator
220 -- after type-checking, a type abstraction to be
221 -- applied to the type of the local environment tuple
222 (Maybe Fixity) -- fixity (filled in by the renamer), for forms that
223 -- were converted from OpApp's by the renamer
224 [HsCmdTop id] -- argument commands
230 These constructors only appear temporarily in the parser.
231 The renamer translates them into the Right Thing.
234 | EWildPat -- wildcard
236 | EAsPat id -- as pattern
239 | ELazyPat (HsExpr id) -- ~ pattern
241 | HsType (HsType id) -- Explicit type argument; e.g f {| Int |} x y
244 Everything from here on appears only in typechecker output.
247 | TyLam -- TRANSLATION
250 | TyApp -- TRANSLATION
251 (HsExpr id) -- generated by Spec
254 -- DictLam and DictApp are "inverses"
262 type PendingSplice = (Name, HsExpr Id) -- Typechecked splices, waiting to be
263 -- pasted back in by the desugarer
266 Table of bindings of names used in rebindable syntax.
267 This gets filled in by the renamer.
270 type ReboundNames id = [(Name, HsExpr id)]
271 -- * Before the renamer, this list is empty
273 -- * After the renamer, it takes the form [(std_name, HsVar actual_name)]
274 -- For example, for the 'return' op of a monad
275 -- normal case: (GHC.Base.return, HsVar GHC.Base.return)
276 -- with rebindable syntax: (GHC.Base.return, return_22)
277 -- where return_22 is whatever "return" is in scope
279 -- * After the type checker, it takes the form [(std_name, <expression>)]
280 -- where <expression> is the evidence for the method
283 A @Dictionary@, unless of length 0 or 1, becomes a tuple. A
284 @ClassDictLam dictvars methods expr@ is, therefore:
286 \ x -> case x of ( dictvars-and-methods-tuple ) -> expr
290 instance OutputableBndr id => Outputable (HsExpr id) where
291 ppr expr = pprExpr expr
295 pprExpr :: OutputableBndr id => HsExpr id -> SDoc
297 pprExpr e = pprDeeper (ppr_expr e)
298 pprBinds b = pprDeeper (ppr b)
300 ppr_expr (HsVar v) = pprHsVar v
301 ppr_expr (HsIPVar v) = ppr v
302 ppr_expr (HsLit lit) = ppr lit
303 ppr_expr (HsOverLit lit) = ppr lit
305 ppr_expr (HsLam match) = pprMatch LambdaExpr match
307 ppr_expr expr@(HsApp e1 e2)
308 = let (fun, args) = collect_args expr [] in
309 (ppr_expr fun) <+> (sep (map pprParendExpr args))
311 collect_args (HsApp fun arg) args = collect_args fun (arg:args)
312 collect_args fun args = (fun, args)
314 ppr_expr (OpApp e1 op fixity e2)
316 HsVar v -> pp_infixly v
319 pp_e1 = pprParendExpr e1 -- Add parens to make precedence clear
320 pp_e2 = pprParendExpr e2
323 = hang (ppr_expr op) 4 (sep [pp_e1, pp_e2])
326 = sep [pp_e1, hsep [pprInfix v, pp_e2]]
328 ppr_expr (NegApp e _) = char '-' <+> pprParendExpr e
330 ppr_expr (HsPar e) = parens (ppr_expr e)
332 ppr_expr (SectionL expr op)
334 HsVar v -> pp_infixly v
337 pp_expr = pprParendExpr expr
339 pp_prefixly = hang (hsep [text " \\ x_ ->", ppr op])
340 4 (hsep [pp_expr, ptext SLIT("x_ )")])
341 pp_infixly v = parens (sep [pp_expr, ppr v])
343 ppr_expr (SectionR op expr)
345 HsVar v -> pp_infixly v
348 pp_expr = pprParendExpr expr
350 pp_prefixly = hang (hsep [text "( \\ x_ ->", ppr op, ptext SLIT("x_")])
351 4 ((<>) pp_expr rparen)
353 = parens (sep [ppr v, pp_expr])
355 ppr_expr (HsCase expr matches _)
356 = sep [ sep [ptext SLIT("case"), nest 4 (pprExpr expr), ptext SLIT("of")],
357 nest 2 (pprMatches CaseAlt matches) ]
359 ppr_expr (HsIf e1 e2 e3 _)
360 = sep [hsep [ptext SLIT("if"), nest 2 (pprExpr e1), ptext SLIT("then")],
365 -- special case: let ... in let ...
366 ppr_expr (HsLet binds expr@(HsLet _ _))
367 = sep [hang (ptext SLIT("let")) 2 (hsep [pprBinds binds, ptext SLIT("in")]),
370 ppr_expr (HsLet binds expr)
371 = sep [hang (ptext SLIT("let")) 2 (pprBinds binds),
372 hang (ptext SLIT("in")) 2 (ppr expr)]
374 ppr_expr (HsDo do_or_list_comp stmts _ _ _) = pprDo do_or_list_comp stmts
376 ppr_expr (ExplicitList _ exprs)
377 = brackets (fsep (punctuate comma (map ppr_expr exprs)))
379 ppr_expr (ExplicitPArr _ exprs)
380 = pa_brackets (fsep (punctuate comma (map ppr_expr exprs)))
382 ppr_expr (ExplicitTuple exprs boxity)
383 = tupleParens boxity (sep (punctuate comma (map ppr_expr exprs)))
385 ppr_expr (RecordCon con_id rbinds)
386 = pp_rbinds (ppr con_id) rbinds
387 ppr_expr (RecordConOut data_con con rbinds)
388 = pp_rbinds (ppr con) rbinds
390 ppr_expr (RecordUpd aexp rbinds)
391 = pp_rbinds (pprParendExpr aexp) rbinds
392 ppr_expr (RecordUpdOut aexp _ _ rbinds)
393 = pp_rbinds (pprParendExpr aexp) rbinds
395 ppr_expr (ExprWithTySig expr sig)
396 = hang (nest 2 (ppr_expr expr) <+> dcolon)
399 ppr_expr (ArithSeqIn info)
400 = brackets (ppr info)
401 ppr_expr (ArithSeqOut expr info)
402 = brackets (ppr info)
404 ppr_expr (PArrSeqIn info)
405 = pa_brackets (ppr info)
406 ppr_expr (PArrSeqOut expr info)
407 = pa_brackets (ppr info)
409 ppr_expr EWildPat = char '_'
410 ppr_expr (ELazyPat e) = char '~' <> pprParendExpr e
411 ppr_expr (EAsPat v e) = ppr v <> char '@' <> pprParendExpr e
413 ppr_expr (HsSCC lbl expr)
414 = sep [ ptext SLIT("_scc_") <+> doubleQuotes (ftext lbl), pprParendExpr expr ]
416 ppr_expr (TyLam tyvars expr)
417 = hang (hsep [ptext SLIT("/\\"),
418 hsep (map (pprBndr LambdaBind) tyvars),
422 ppr_expr (TyApp expr [ty])
423 = hang (ppr_expr expr) 4 (pprParendType ty)
425 ppr_expr (TyApp expr tys)
426 = hang (ppr_expr expr)
427 4 (brackets (interpp'SP tys))
429 ppr_expr (DictLam dictvars expr)
430 = hang (hsep [ptext SLIT("\\{-dict-}"),
431 hsep (map (pprBndr LambdaBind) dictvars),
435 ppr_expr (DictApp expr [dname])
436 = hang (ppr_expr expr) 4 (ppr dname)
438 ppr_expr (DictApp expr dnames)
439 = hang (ppr_expr expr)
440 4 (brackets (interpp'SP dnames))
442 ppr_expr (HsType id) = ppr id
444 ppr_expr (HsSplice n e _) = char '$' <> brackets (ppr n) <> pprParendExpr e
445 ppr_expr (HsBracket b _) = pprHsBracket b
446 ppr_expr (HsBracketOut e ps) = ppr e $$ ptext SLIT("where") <+> ppr ps
447 ppr_expr (HsReify r) = ppr r
449 ppr_expr (HsProc pat (HsCmdTop cmd _ _ _) _)
450 = hsep [ptext SLIT("proc"), ppr pat, ptext SLIT("->"), pprExpr cmd]
452 ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp True _)
453 = hsep [ppr_expr arrow, ptext SLIT("-<"), ppr_expr arg]
454 ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp False _)
455 = hsep [ppr_expr arg, ptext SLIT(">-"), ppr_expr arrow]
456 ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp True _)
457 = hsep [ppr_expr arrow, ptext SLIT("-<<"), ppr_expr arg]
458 ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp False _)
459 = hsep [ppr_expr arg, ptext SLIT(">>-"), ppr_expr arrow]
461 ppr_expr (HsArrForm (HsVar v) (Just _) [arg1, arg2] _)
462 = sep [pprCmdArg arg1, hsep [pprInfix v, pprCmdArg arg2]]
463 ppr_expr (HsArrForm op _ args _)
464 = hang (ptext SLIT("(|") <> ppr_expr op)
465 4 (sep (map pprCmdArg args) <> ptext SLIT("|)"))
467 pprCmdArg :: OutputableBndr id => HsCmdTop id -> SDoc
468 pprCmdArg (HsCmdTop cmd@(HsArrForm _ Nothing [] _) _ _ _) = ppr_expr cmd
469 pprCmdArg (HsCmdTop cmd _ _ _) = parens (ppr_expr cmd)
471 -- Put a var in backquotes if it's not an operator already
472 pprInfix :: Outputable name => name -> SDoc
473 pprInfix v | isOperator ppr_v = ppr_v
474 | otherwise = char '`' <> ppr_v <> char '`'
478 -- add parallel array brackets around a document
480 pa_brackets :: SDoc -> SDoc
481 pa_brackets p = ptext SLIT("[:") <> p <> ptext SLIT(":]")
484 Parenthesize unless very simple:
486 pprParendExpr :: OutputableBndr id => HsExpr id -> SDoc
490 pp_as_was = ppr_expr expr
491 -- Using ppr_expr here avoids the call to 'deeper'
492 -- Not sure if that's always right.
499 HsIPVar _ -> pp_as_was
500 ExplicitList _ _ -> pp_as_was
501 ExplicitPArr _ _ -> pp_as_was
502 ExplicitTuple _ _ -> pp_as_was
505 _ -> parens pp_as_was
508 %************************************************************************
510 \subsection{Commands (in arrow abstractions)}
512 %************************************************************************
514 We re-use HsExpr to represent these.
517 type HsCmd id = HsExpr id
519 data HsArrAppType = HsHigherOrderApp | HsFirstOrderApp
522 The legal constructors for commands are:
524 = HsArrApp ... -- as above
526 | HsArrForm ... -- as above
531 | HsLam (Match id) -- kappa
533 -- the renamer turns this one into HsArrForm
534 | OpApp (HsExpr id) -- left operand
535 (HsCmd id) -- operator
536 Fixity -- Renamer adds fixity; bottom until then
537 (HsCmd id) -- right operand
539 | HsPar (HsCmd id) -- parenthesised command
542 [Match id] -- bodies are HsCmd's
545 | HsIf (HsExpr id) -- predicate
546 (HsCmd id) -- then part
547 (HsCmd id) -- else part
550 | HsLet (HsBinds id) -- let(rec)
553 | HsDo (HsStmtContext Name) -- The parameterisation is unimportant
554 -- because in this context we never use
555 -- the PatGuard or ParStmt variant
556 [Stmt id] -- HsExpr's are really HsCmd's
558 PostTcType -- Type of the whole expression
561 Top-level command, introducing a new arrow.
562 This may occur inside a proc (where the stack is empty) or as an
563 argument of a command-forming operator.
567 = HsCmdTop (HsCmd id)
568 [PostTcType] -- types of inputs on the command's stack
569 PostTcType -- return type of the command
571 -- after type checking:
572 -- names used in the command's desugaring
575 %************************************************************************
577 \subsection{Record binds}
579 %************************************************************************
582 type HsRecordBinds id = [(id, HsExpr id)]
584 recBindFields :: HsRecordBinds id -> [id]
585 recBindFields rbinds = [field | (field,_) <- rbinds]
587 pp_rbinds :: OutputableBndr id => SDoc -> HsRecordBinds id -> SDoc
589 pp_rbinds thing rbinds
591 4 (braces (sep (punctuate comma (map (pp_rbind) rbinds))))
593 pp_rbind (v, e) = hsep [pprBndr LetBind v, char '=', ppr e]
598 %************************************************************************
600 \subsection{@Match@, @GRHSs@, and @GRHS@ datatypes}
602 %************************************************************************
604 @Match@es are sets of pattern bindings and right hand sides for
605 functions, patterns or case branches. For example, if a function @g@
611 then \tr{g} has two @Match@es: @(x,y) = y@ and @((x:ys),y) = y+1@.
613 It is always the case that each element of an @[Match]@ list has the
614 same number of @pats@s inside it. This corresponds to saying that
615 a function defined by pattern matching must have the same number of
616 patterns in each equation.
621 [Pat id] -- The patterns
622 (Maybe (HsType id)) -- A type signature for the result of the match
623 -- Nothing after typechecking
627 -- GRHSs are used both for pattern bindings and for Matches
629 = GRHSs [GRHS id] -- Guarded RHSs
630 (HsBinds id) -- The where clause
631 PostTcType -- Type of RHS (after type checking)
634 = GRHS [Stmt id] -- The RHS is the final ResultStmt
638 @getMatchLoc@ takes a @Match@ and returns the
639 source-location gotten from the GRHS inside.
640 THis is something of a nuisance, but no more.
643 getMatchLoc :: Match id -> SrcLoc
644 getMatchLoc (Match _ _ (GRHSs (GRHS _ loc : _) _ _)) = loc
647 We know the list must have at least one @Match@ in it.
650 pprMatches :: (OutputableBndr id) => HsMatchContext id -> [Match id] -> SDoc
651 pprMatches ctxt matches = vcat (map (pprMatch ctxt) matches)
653 -- Exported to HsBinds, which can't see the defn of HsMatchContext
654 pprFunBind :: (OutputableBndr id) => id -> [Match id] -> SDoc
655 pprFunBind fun matches = pprMatches (FunRhs fun) matches
657 -- Exported to HsBinds, which can't see the defn of HsMatchContext
658 pprPatBind :: (OutputableBndr id)
659 => Pat id -> GRHSs id -> SDoc
660 pprPatBind pat grhss = sep [ppr pat, nest 4 (pprGRHSs PatBindRhs grhss)]
663 pprMatch :: OutputableBndr id => HsMatchContext id -> Match id -> SDoc
664 pprMatch ctxt (Match pats maybe_ty grhss)
665 = pp_name ctxt <+> sep [sep (map ppr pats),
667 nest 2 (pprGRHSs ctxt grhss)]
669 pp_name (FunRhs fun) = ppr fun -- Not pprBndr; the AbsBinds will
670 -- have printed the signature
671 pp_name LambdaExpr = char '\\'
672 pp_name other = empty
674 ppr_maybe_ty = case maybe_ty of
675 Just ty -> dcolon <+> ppr ty
679 pprGRHSs :: OutputableBndr id => HsMatchContext id -> GRHSs id -> SDoc
680 pprGRHSs ctxt (GRHSs grhss binds ty)
681 = vcat (map (pprGRHS ctxt) grhss)
683 (if nullBinds binds then empty
684 else text "where" $$ nest 4 (pprDeeper (ppr binds)))
687 pprGRHS :: OutputableBndr id => HsMatchContext id -> GRHS id -> SDoc
689 pprGRHS ctxt (GRHS [ResultStmt expr _] locn)
692 pprGRHS ctxt (GRHS guarded locn)
693 = sep [char '|' <+> interpp'SP guards, pp_rhs ctxt expr]
695 ResultStmt expr _ = last guarded -- Last stmt should be a ResultStmt for guards
696 guards = init guarded
698 pp_rhs ctxt rhs = matchSeparator ctxt <+> pprDeeper (ppr rhs)
703 %************************************************************************
705 \subsection{Do stmts and list comprehensions}
707 %************************************************************************
711 = BindStmt (Pat id) (HsExpr id) SrcLoc
712 | LetStmt (HsBinds id)
713 | ResultStmt (HsExpr id) SrcLoc -- See notes that follow
714 | ExprStmt (HsExpr id) PostTcType SrcLoc -- See notes that follow
715 -- The type is the *element type* of the expression
717 -- ParStmts only occur in a list comprehension
718 | ParStmt [([Stmt id], [id])] -- After remaing, the ids are the binders
719 -- bound by the stmts and used subsequently
721 -- Recursive statement
723 --- The next two fields are only valid after renaming
724 [id] -- The ids are a subset of the variables bound by the stmts
725 -- that are used in stmts that follow the RecStmt
727 [id] -- Ditto, but these variables are the "recursive" ones, that
728 -- are used before they are bound in the stmts of the RecStmt
729 -- From a type-checking point of view, these ones have to be monomorphic
731 --- This field is only valid after typechecking
732 [HsExpr id] -- These expressions correspond
733 -- 1-to-1 with the "recursive" [id], and are the expresions that
734 -- should be returned by the recursion. They may not quite be the
735 -- Ids themselves, because the Id may be *polymorphic*, but
736 -- the returned thing has to be *monomorphic*.
739 ExprStmts and ResultStmts are a bit tricky, because what they mean
740 depends on the context. Consider the following contexts:
742 A do expression of type (m res_ty)
743 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
744 * ExprStmt E any_ty: do { ....; E; ... }
746 Translation: E >> ...
748 * ResultStmt E: do { ....; E }
752 A list comprehensions of type [elt_ty]
753 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
754 * ExprStmt E Bool: [ .. | .... E ]
756 [ .. | .... | ..., E | ... ]
758 Translation: if E then fail else ...
760 * ResultStmt E: [ E | ... ]
762 Translation: return E
764 A guard list, guarding a RHS of type rhs_ty
765 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
766 * ExprStmt E Bool: f x | ..., E, ... = ...rhs...
768 Translation: if E then fail else ...
770 * ResultStmt E: f x | ...guards... = E
774 Array comprehensions are handled like list comprehensions -=chak
777 consLetStmt :: HsBinds id -> [Stmt id] -> [Stmt id]
778 consLetStmt EmptyBinds stmts = stmts
779 consLetStmt binds stmts = LetStmt binds : stmts
783 instance OutputableBndr id => Outputable (Stmt id) where
784 ppr stmt = pprStmt stmt
786 pprStmt (BindStmt pat expr _) = hsep [ppr pat, ptext SLIT("<-"), ppr expr]
787 pprStmt (LetStmt binds) = hsep [ptext SLIT("let"), pprBinds binds]
788 pprStmt (ExprStmt expr _ _) = ppr expr
789 pprStmt (ResultStmt expr _) = ppr expr
790 pprStmt (ParStmt stmtss) = hsep (map (\stmts -> ptext SLIT("| ") <> ppr stmts) stmtss)
791 pprStmt (RecStmt segment _ _ _) = ptext SLIT("rec") <+> braces (vcat (map ppr segment))
793 pprDo :: OutputableBndr id => HsStmtContext any -> [Stmt id] -> SDoc
794 pprDo DoExpr stmts = hang (ptext SLIT("do")) 2 (vcat (map ppr stmts))
795 pprDo MDoExpr stmts = hang (ptext SLIT("mdo")) 3 (vcat (map ppr stmts))
796 pprDo ListComp stmts = pprComp brackets stmts
797 pprDo PArrComp stmts = pprComp pa_brackets stmts
799 pprComp :: OutputableBndr id => (SDoc -> SDoc) -> [Stmt id] -> SDoc
800 pprComp brack stmts = brack $
801 hang (pprExpr expr <+> char '|')
804 ResultStmt expr _ = last stmts -- Last stmt should
805 quals = init stmts -- be an ResultStmt
808 %************************************************************************
810 Template Haskell quotation brackets
812 %************************************************************************
815 data HsBracket id = ExpBr (HsExpr id)
820 instance OutputableBndr id => Outputable (HsBracket id) where
824 pprHsBracket (ExpBr e) = thBrackets empty (ppr e)
825 pprHsBracket (PatBr p) = thBrackets (char 'p') (ppr p)
826 pprHsBracket (DecBr d) = thBrackets (char 'd') (ppr d)
827 pprHsBracket (TypBr t) = thBrackets (char 't') (ppr t)
830 thBrackets pp_kind pp_body = char '[' <> pp_kind <> char '|' <+>
831 pp_body <+> ptext SLIT("|]")
833 data HsReify id = Reify ReifyFlavour id -- Pre typechecking
834 | ReifyOut ReifyFlavour Name -- Post typechecking
835 -- The Name could be the name of
836 -- an Id, TyCon, or Class
838 data ReifyFlavour = ReifyDecl | ReifyType | ReifyFixity
840 instance Outputable id => Outputable (HsReify id) where
841 ppr (Reify flavour id) = ppr flavour <+> ppr id
842 ppr (ReifyOut flavour thing) = ppr flavour <+> ppr thing
844 instance Outputable ReifyFlavour where
845 ppr ReifyDecl = ptext SLIT("reifyDecl")
846 ppr ReifyType = ptext SLIT("reifyType")
847 ppr ReifyFixity = ptext SLIT("reifyFixity")
850 %************************************************************************
852 \subsection{Enumerations and list comprehensions}
854 %************************************************************************
859 | FromThen (HsExpr id)
863 | FromThenTo (HsExpr id)
869 instance OutputableBndr id => Outputable (ArithSeqInfo id) where
870 ppr (From e1) = hcat [ppr e1, pp_dotdot]
871 ppr (FromThen e1 e2) = hcat [ppr e1, comma, space, ppr e2, pp_dotdot]
872 ppr (FromTo e1 e3) = hcat [ppr e1, pp_dotdot, ppr e3]
873 ppr (FromThenTo e1 e2 e3)
874 = hcat [ppr e1, comma, space, ppr e2, pp_dotdot, ppr e3]
876 pp_dotdot = ptext SLIT(" .. ")
880 %************************************************************************
882 \subsection{HsMatchCtxt}
884 %************************************************************************
887 data HsMatchContext id -- Context of a Match
888 = FunRhs id -- Function binding for f
889 | CaseAlt -- Guard on a case alternative
890 | LambdaExpr -- Pattern of a lambda
891 | ProcExpr -- Pattern of a proc
892 | PatBindRhs -- Pattern binding
893 | RecUpd -- Record update [used only in DsExpr to tell matchWrapper
894 -- what sort of runtime error message to generate]
895 | StmtCtxt (HsStmtContext id) -- Pattern of a do-stmt or list comprehension
898 data HsStmtContext id
901 | MDoExpr -- Recursive do-expression
902 | PArrComp -- Parallel array comprehension
903 | PatGuard (HsMatchContext id) -- Pattern guard for specified thing
904 | ParStmtCtxt (HsStmtContext id) -- A branch of a parallel stmt
908 isDoExpr :: HsStmtContext id -> Bool
909 isDoExpr DoExpr = True
910 isDoExpr MDoExpr = True
911 isDoExpr other = False
915 matchSeparator (FunRhs _) = ptext SLIT("=")
916 matchSeparator CaseAlt = ptext SLIT("->")
917 matchSeparator LambdaExpr = ptext SLIT("->")
918 matchSeparator ProcExpr = ptext SLIT("->")
919 matchSeparator PatBindRhs = ptext SLIT("=")
920 matchSeparator (StmtCtxt _) = ptext SLIT("<-")
921 matchSeparator RecUpd = panic "unused"
925 pprMatchContext (FunRhs fun) = ptext SLIT("the definition of") <+> quotes (ppr fun)
926 pprMatchContext CaseAlt = ptext SLIT("a case alternative")
927 pprMatchContext RecUpd = ptext SLIT("a record-update construct")
928 pprMatchContext PatBindRhs = ptext SLIT("a pattern binding")
929 pprMatchContext LambdaExpr = ptext SLIT("a lambda abstraction")
930 pprMatchContext ProcExpr = ptext SLIT("an arrow abstraction")
931 pprMatchContext (StmtCtxt ctxt) = ptext SLIT("a pattern binding in") $$ pprStmtContext ctxt
933 pprMatchRhsContext (FunRhs fun) = ptext SLIT("a right-hand side of function") <+> quotes (ppr fun)
934 pprMatchRhsContext CaseAlt = ptext SLIT("the body of a case alternative")
935 pprMatchRhsContext PatBindRhs = ptext SLIT("the right-hand side of a pattern binding")
936 pprMatchRhsContext LambdaExpr = ptext SLIT("the body of a lambda")
937 pprMatchRhsContext ProcExpr = ptext SLIT("the body of a proc")
938 pprMatchRhsContext RecUpd = panic "pprMatchRhsContext"
940 pprStmtContext (ParStmtCtxt c) = sep [ptext SLIT("a parallel branch of"), pprStmtContext c]
941 pprStmtContext (PatGuard ctxt) = ptext SLIT("a pattern guard for") $$ pprMatchContext ctxt
942 pprStmtContext DoExpr = ptext SLIT("a 'do' expression")
943 pprStmtContext MDoExpr = ptext SLIT("an 'mdo' expression")
944 pprStmtContext ListComp = ptext SLIT("a list comprehension")
945 pprStmtContext PArrComp = ptext SLIT("an array comprehension")
947 -- Used for the result statement of comprehension
948 -- e.g. the 'e' in [ e | ... ]
949 -- or the 'r' in f x = r
950 pprStmtResultContext (PatGuard ctxt) = pprMatchRhsContext ctxt
951 pprStmtResultContext other = ptext SLIT("the result of") <+> pprStmtContext other
954 -- Used to generate the string for a *runtime* error message
955 matchContextErrString (FunRhs fun) = "function " ++ showSDoc (ppr fun)
956 matchContextErrString CaseAlt = "case"
957 matchContextErrString PatBindRhs = "pattern binding"
958 matchContextErrString RecUpd = "record update"
959 matchContextErrString LambdaExpr = "lambda"
960 matchContextErrString ProcExpr = "proc"
961 matchContextErrString (StmtCtxt (ParStmtCtxt c)) = matchContextErrString (StmtCtxt c)
962 matchContextErrString (StmtCtxt (PatGuard _)) = "pattern guard"
963 matchContextErrString (StmtCtxt DoExpr) = "'do' expression"
964 matchContextErrString (StmtCtxt MDoExpr) = "'mdo' expression"
965 matchContextErrString (StmtCtxt ListComp) = "list comprehension"
966 matchContextErrString (StmtCtxt PArrComp) = "array comprehension"