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 pprParendExpr 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 (ppr_expr 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 [ppr_expr arrow, ptext SLIT("-<"), ppr_expr arg]
440 ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp False _)
441 = hsep [ppr_expr arg, ptext SLIT(">-"), ppr_expr arrow]
442 ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp True _)
443 = hsep [ppr_expr arrow, ptext SLIT("-<<"), ppr_expr arg]
444 ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp False _)
445 = hsep [ppr_expr arg, ptext SLIT(">>-"), ppr_expr 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("(|") <> ppr_expr op)
451 4 (sep (map pprCmdArg args) <> ptext SLIT("|)"))
453 pprCmdArg :: OutputableBndr id => HsCmdTop id -> SDoc
454 pprCmdArg (HsCmdTop cmd@(HsArrForm _ Nothing [] _) _ _ _) = ppr_expr cmd
455 pprCmdArg (HsCmdTop cmd _ _ _) = parens (ppr_expr 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 = ppr_expr expr
477 -- Using ppr_expr here avoids the call to 'deeper'
478 -- Not sure if that's always right.
485 HsIPVar _ -> pp_as_was
486 ExplicitList _ _ -> pp_as_was
487 ExplicitPArr _ _ -> pp_as_was
488 ExplicitTuple _ _ -> pp_as_was
491 _ -> parens pp_as_was
494 %************************************************************************
496 \subsection{Commands (in arrow abstractions)}
498 %************************************************************************
500 We re-use HsExpr to represent these.
503 type HsCmd id = HsExpr id
505 data HsArrAppType = HsHigherOrderApp | HsFirstOrderApp
508 The legal constructors for commands are:
510 = HsArrApp ... -- as above
512 | HsArrForm ... -- as above
517 | HsLam (Match id) -- kappa
519 -- the renamer turns this one into HsArrForm
520 | OpApp (HsExpr id) -- left operand
521 (HsCmd id) -- operator
522 Fixity -- Renamer adds fixity; bottom until then
523 (HsCmd id) -- right operand
525 | HsPar (HsCmd id) -- parenthesised command
528 [Match id] -- bodies are HsCmd's
531 | HsIf (HsExpr id) -- predicate
532 (HsCmd id) -- then part
533 (HsCmd id) -- else part
536 | HsLet (HsBinds id) -- let(rec)
539 | HsDo (HsStmtContext Name) -- The parameterisation is unimportant
540 -- because in this context we never use
541 -- the PatGuard or ParStmt variant
542 [Stmt id] -- HsExpr's are really HsCmd's
544 PostTcType -- Type of the whole expression
547 Top-level command, introducing a new arrow.
548 This may occur inside a proc (where the stack is empty) or as an
549 argument of a command-forming operator.
553 = HsCmdTop (HsCmd id)
554 [PostTcType] -- types of inputs on the command's stack
555 PostTcType -- return type of the command
557 -- after type checking:
558 -- names used in the command's desugaring
561 %************************************************************************
563 \subsection{Record binds}
565 %************************************************************************
568 type HsRecordBinds id = [(id, HsExpr id)]
570 recBindFields :: HsRecordBinds id -> [id]
571 recBindFields rbinds = [field | (field,_) <- rbinds]
573 pp_rbinds :: OutputableBndr id => SDoc -> HsRecordBinds id -> SDoc
575 pp_rbinds thing rbinds
577 4 (braces (sep (punctuate comma (map (pp_rbind) rbinds))))
579 pp_rbind (v, e) = hsep [pprBndr LetBind v, char '=', ppr e]
584 %************************************************************************
586 \subsection{@Match@, @GRHSs@, and @GRHS@ datatypes}
588 %************************************************************************
590 @Match@es are sets of pattern bindings and right hand sides for
591 functions, patterns or case branches. For example, if a function @g@
597 then \tr{g} has two @Match@es: @(x,y) = y@ and @((x:ys),y) = y+1@.
599 It is always the case that each element of an @[Match]@ list has the
600 same number of @pats@s inside it. This corresponds to saying that
601 a function defined by pattern matching must have the same number of
602 patterns in each equation.
607 [Pat id] -- The patterns
608 (Maybe (HsType id)) -- A type signature for the result of the match
609 -- Nothing after typechecking
613 -- GRHSs are used both for pattern bindings and for Matches
615 = GRHSs [GRHS id] -- Guarded RHSs
616 (HsBinds id) -- The where clause
617 PostTcType -- Type of RHS (after type checking)
620 = GRHS [Stmt id] -- The RHS is the final ResultStmt
623 mkSimpleMatch :: [Pat id] -> HsExpr id -> Type -> SrcLoc -> Match id
624 mkSimpleMatch pats rhs rhs_ty locn
625 = Match pats Nothing (GRHSs (unguardedRHS rhs locn) EmptyBinds rhs_ty)
627 unguardedRHS :: HsExpr id -> SrcLoc -> [GRHS id]
628 unguardedRHS rhs loc = [GRHS [ResultStmt rhs loc] loc]
630 glueBindsOnGRHSs :: HsBinds id -> GRHSs id -> GRHSs id
631 glueBindsOnGRHSs EmptyBinds grhss = grhss
632 glueBindsOnGRHSs binds1 (GRHSs grhss binds2 ty)
633 = GRHSs grhss (binds1 `ThenBinds` binds2) ty
636 @getMatchLoc@ takes a @Match@ and returns the
637 source-location gotten from the GRHS inside.
638 THis is something of a nuisance, but no more.
641 getMatchLoc :: Match id -> SrcLoc
642 getMatchLoc (Match _ _ (GRHSs (GRHS _ loc : _) _ _)) = loc
645 We know the list must have at least one @Match@ in it.
648 pprMatches :: (OutputableBndr id) => HsMatchContext id -> [Match id] -> SDoc
649 pprMatches ctxt matches = vcat (map (pprMatch ctxt) matches)
651 -- Exported to HsBinds, which can't see the defn of HsMatchContext
652 pprFunBind :: (OutputableBndr id) => id -> [Match id] -> SDoc
653 pprFunBind fun matches = pprMatches (FunRhs fun) matches
655 -- Exported to HsBinds, which can't see the defn of HsMatchContext
656 pprPatBind :: (OutputableBndr id)
657 => Pat id -> GRHSs id -> SDoc
658 pprPatBind pat grhss = sep [ppr pat, nest 4 (pprGRHSs PatBindRhs grhss)]
661 pprMatch :: OutputableBndr id => HsMatchContext id -> Match id -> SDoc
662 pprMatch ctxt (Match pats maybe_ty grhss)
663 = pp_name ctxt <+> sep [sep (map ppr pats),
665 nest 2 (pprGRHSs ctxt grhss)]
667 pp_name (FunRhs fun) = ppr fun -- Not pprBndr; the AbsBinds will
668 -- have printed the signature
669 pp_name LambdaExpr = char '\\'
670 pp_name other = empty
672 ppr_maybe_ty = case maybe_ty of
673 Just ty -> dcolon <+> ppr ty
677 pprGRHSs :: OutputableBndr id => HsMatchContext id -> GRHSs id -> SDoc
678 pprGRHSs ctxt (GRHSs grhss binds ty)
679 = vcat (map (pprGRHS ctxt) grhss)
681 (if nullBinds binds then empty
682 else text "where" $$ nest 4 (pprDeeper (ppr binds)))
685 pprGRHS :: OutputableBndr id => HsMatchContext id -> GRHS id -> SDoc
687 pprGRHS ctxt (GRHS [ResultStmt expr _] locn)
690 pprGRHS ctxt (GRHS guarded locn)
691 = sep [char '|' <+> interpp'SP guards, pp_rhs ctxt expr]
693 ResultStmt expr _ = last guarded -- Last stmt should be a ResultStmt for guards
694 guards = init guarded
696 pp_rhs ctxt rhs = matchSeparator ctxt <+> pprDeeper (ppr rhs)
701 %************************************************************************
703 \subsection{Do stmts and list comprehensions}
705 %************************************************************************
709 = BindStmt (Pat id) (HsExpr id) SrcLoc
710 | LetStmt (HsBinds id)
711 | ResultStmt (HsExpr id) SrcLoc -- See notes that follow
712 | ExprStmt (HsExpr id) PostTcType SrcLoc -- See notes that follow
713 -- The type is the *element type* of the expression
715 -- ParStmts only occur in a list comprehension
716 | ParStmt [([Stmt id], [id])] -- After remaing, the ids are the binders
717 -- bound by the stmts and used subsequently
719 -- Recursive statement
721 --- The next two fields are only valid after renaming
722 [id] -- The ids are a subset of the variables bound by the stmts
723 -- that are used in stmts that follow the RecStmt
725 [id] -- Ditto, but these variables are the "recursive" ones, that
726 -- are used before they are bound in the stmts of the RecStmt
727 -- From a type-checking point of view, these ones have to be monomorphic
729 --- This field is only valid after typechecking
730 [HsExpr id] -- These expressions correspond
731 -- 1-to-1 with the "recursive" [id], and are the expresions that
732 -- should be returned by the recursion. They may not quite be the
733 -- Ids themselves, because the Id may be *polymorphic*, but
734 -- the returned thing has to be *monomorphic*.
737 ExprStmts and ResultStmts are a bit tricky, because what they mean
738 depends on the context. Consider the following contexts:
740 A do expression of type (m res_ty)
741 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
742 * ExprStmt E any_ty: do { ....; E; ... }
744 Translation: E >> ...
746 * ResultStmt E: do { ....; E }
750 A list comprehensions of type [elt_ty]
751 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
752 * ExprStmt E Bool: [ .. | .... E ]
754 [ .. | .... | ..., E | ... ]
756 Translation: if E then fail else ...
758 * ResultStmt E: [ E | ... ]
760 Translation: return E
762 A guard list, guarding a RHS of type rhs_ty
763 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
764 * ExprStmt E Bool: f x | ..., E, ... = ...rhs...
766 Translation: if E then fail else ...
768 * ResultStmt E: f x | ...guards... = E
772 Array comprehensions are handled like list comprehensions -=chak
775 consLetStmt :: HsBinds id -> [Stmt id] -> [Stmt id]
776 consLetStmt EmptyBinds stmts = stmts
777 consLetStmt binds stmts = LetStmt binds : stmts
781 instance OutputableBndr id => Outputable (Stmt id) where
782 ppr stmt = pprStmt stmt
784 pprStmt (BindStmt pat expr _) = hsep [ppr pat, ptext SLIT("<-"), ppr expr]
785 pprStmt (LetStmt binds) = hsep [ptext SLIT("let"), pprBinds binds]
786 pprStmt (ExprStmt expr _ _) = ppr expr
787 pprStmt (ResultStmt expr _) = ppr expr
788 pprStmt (ParStmt stmtss) = hsep (map (\stmts -> ptext SLIT("| ") <> ppr stmts) stmtss)
789 pprStmt (RecStmt segment _ _ _) = ptext SLIT("rec") <+> braces (vcat (map ppr segment))
791 pprDo :: OutputableBndr id => HsStmtContext any -> [Stmt id] -> SDoc
792 pprDo DoExpr stmts = hang (ptext SLIT("do")) 2 (vcat (map ppr stmts))
793 pprDo MDoExpr stmts = hang (ptext SLIT("mdo")) 3 (vcat (map ppr stmts))
794 pprDo ListComp stmts = pprComp brackets stmts
795 pprDo PArrComp stmts = pprComp pa_brackets stmts
797 pprComp :: OutputableBndr id => (SDoc -> SDoc) -> [Stmt id] -> SDoc
798 pprComp brack stmts = brack $
799 hang (pprExpr expr <+> char '|')
802 ResultStmt expr _ = last stmts -- Last stmt should
803 quals = init stmts -- be an ResultStmt
806 %************************************************************************
808 Template Haskell quotation brackets
810 %************************************************************************
813 data HsBracket id = ExpBr (HsExpr id)
818 instance OutputableBndr id => Outputable (HsBracket id) where
822 pprHsBracket (ExpBr e) = thBrackets empty (ppr e)
823 pprHsBracket (PatBr p) = thBrackets (char 'p') (ppr p)
824 pprHsBracket (DecBr d) = thBrackets (char 'd') (ppr d)
825 pprHsBracket (TypBr t) = thBrackets (char 't') (ppr t)
828 thBrackets pp_kind pp_body = char '[' <> pp_kind <> char '|' <+>
829 pp_body <+> ptext SLIT("|]")
831 data HsReify id = Reify ReifyFlavour id -- Pre typechecking
832 | ReifyOut ReifyFlavour Name -- Post typechecking
833 -- The Name could be the name of
834 -- an Id, TyCon, or Class
836 data ReifyFlavour = ReifyDecl | ReifyType | ReifyFixity
838 instance Outputable id => Outputable (HsReify id) where
839 ppr (Reify flavour id) = ppr flavour <+> ppr id
840 ppr (ReifyOut flavour thing) = ppr flavour <+> ppr thing
842 instance Outputable ReifyFlavour where
843 ppr ReifyDecl = ptext SLIT("reifyDecl")
844 ppr ReifyType = ptext SLIT("reifyType")
845 ppr ReifyFixity = ptext SLIT("reifyFixity")
848 %************************************************************************
850 \subsection{Enumerations and list comprehensions}
852 %************************************************************************
857 | FromThen (HsExpr id)
861 | FromThenTo (HsExpr id)
867 instance OutputableBndr id => Outputable (ArithSeqInfo id) where
868 ppr (From e1) = hcat [ppr e1, pp_dotdot]
869 ppr (FromThen e1 e2) = hcat [ppr e1, comma, space, ppr e2, pp_dotdot]
870 ppr (FromTo e1 e3) = hcat [ppr e1, pp_dotdot, ppr e3]
871 ppr (FromThenTo e1 e2 e3)
872 = hcat [ppr e1, comma, space, ppr e2, pp_dotdot, ppr e3]
874 pp_dotdot = ptext SLIT(" .. ")
878 %************************************************************************
880 \subsection{HsMatchCtxt}
882 %************************************************************************
885 data HsMatchContext id -- Context of a Match
886 = FunRhs id -- Function binding for f
887 | CaseAlt -- Guard on a case alternative
888 | LambdaExpr -- Pattern of a lambda
889 | ProcExpr -- Pattern of a proc
890 | PatBindRhs -- Pattern binding
891 | RecUpd -- Record update [used only in DsExpr to tell matchWrapper
892 -- what sort of runtime error message to generate]
893 | StmtCtxt (HsStmtContext id) -- Pattern of a do-stmt or list comprehension
896 data HsStmtContext id
899 | MDoExpr -- Recursive do-expression
900 | PArrComp -- Parallel array comprehension
901 | PatGuard (HsMatchContext id) -- Pattern guard for specified thing
902 | ParStmtCtxt (HsStmtContext id) -- A branch of a parallel stmt
906 isDoExpr :: HsStmtContext id -> Bool
907 isDoExpr DoExpr = True
908 isDoExpr MDoExpr = True
909 isDoExpr other = False
913 matchSeparator (FunRhs _) = ptext SLIT("=")
914 matchSeparator CaseAlt = ptext SLIT("->")
915 matchSeparator LambdaExpr = ptext SLIT("->")
916 matchSeparator ProcExpr = ptext SLIT("->")
917 matchSeparator PatBindRhs = ptext SLIT("=")
918 matchSeparator (StmtCtxt _) = ptext SLIT("<-")
919 matchSeparator RecUpd = panic "unused"
923 pprMatchContext (FunRhs fun) = ptext SLIT("the definition of") <+> quotes (ppr fun)
924 pprMatchContext CaseAlt = ptext SLIT("a case alternative")
925 pprMatchContext RecUpd = ptext SLIT("a record-update construct")
926 pprMatchContext PatBindRhs = ptext SLIT("a pattern binding")
927 pprMatchContext LambdaExpr = ptext SLIT("a lambda abstraction")
928 pprMatchContext ProcExpr = ptext SLIT("an arrow abstraction")
929 pprMatchContext (StmtCtxt ctxt) = ptext SLIT("a pattern binding in") $$ pprStmtContext ctxt
931 pprMatchRhsContext (FunRhs fun) = ptext SLIT("a right-hand side of function") <+> quotes (ppr fun)
932 pprMatchRhsContext CaseAlt = ptext SLIT("the body of a case alternative")
933 pprMatchRhsContext PatBindRhs = ptext SLIT("the right-hand side of a pattern binding")
934 pprMatchRhsContext LambdaExpr = ptext SLIT("the body of a lambda")
935 pprMatchRhsContext ProcExpr = ptext SLIT("the body of a proc")
936 pprMatchRhsContext RecUpd = panic "pprMatchRhsContext"
938 pprStmtContext (ParStmtCtxt c) = sep [ptext SLIT("a parallel branch of"), pprStmtContext c]
939 pprStmtContext (PatGuard ctxt) = ptext SLIT("a pattern guard for") $$ pprMatchContext ctxt
940 pprStmtContext DoExpr = ptext SLIT("a 'do' expression")
941 pprStmtContext MDoExpr = ptext SLIT("an 'mdo' expression")
942 pprStmtContext ListComp = ptext SLIT("a list comprehension")
943 pprStmtContext PArrComp = ptext SLIT("an array comprehension")
945 -- Used for the result statement of comprehension
946 -- e.g. the 'e' in [ e | ... ]
947 -- or the 'r' in f x = r
948 pprStmtResultContext (PatGuard ctxt) = pprMatchRhsContext ctxt
949 pprStmtResultContext other = ptext SLIT("the result of") <+> pprStmtContext other
952 -- Used to generate the string for a *runtime* error message
953 matchContextErrString (FunRhs fun) = "function " ++ showSDoc (ppr fun)
954 matchContextErrString CaseAlt = "case"
955 matchContextErrString PatBindRhs = "pattern binding"
956 matchContextErrString RecUpd = "record update"
957 matchContextErrString LambdaExpr = "lambda"
958 matchContextErrString ProcExpr = "proc"
959 matchContextErrString (StmtCtxt (ParStmtCtxt c)) = matchContextErrString (StmtCtxt c)
960 matchContextErrString (StmtCtxt (PatGuard _)) = "pattern guard"
961 matchContextErrString (StmtCtxt DoExpr) = "'do' expression"
962 matchContextErrString (StmtCtxt MDoExpr) = "'mdo' expression"
963 matchContextErrString (StmtCtxt ListComp) = "list comprehension"
964 matchContextErrString (StmtCtxt PArrComp) = "array comprehension"