2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
6 HsExpr: Abstract Haskell syntax: expressions
11 #include "HsVersions.h"
31 %************************************************************************
33 \subsection{Expressions proper}
35 %************************************************************************
38 type LHsExpr id = Located (HsExpr id)
40 -------------------------
41 -- PostTcExpr is an evidence expression attached to the
42 -- syntax tree by the type checker (c.f. postTcType)
43 -- We use a PostTcTable where there are a bunch of pieces of
44 -- evidence, more than is convenient to keep individually
45 type PostTcExpr = HsExpr Id
46 type PostTcTable = [(Name, Id)]
48 noPostTcExpr :: PostTcExpr
49 noPostTcExpr = HsLit (HsString FSLIT("noPostTcExpr"))
51 noPostTcTable :: PostTcTable
54 -------------------------
55 -- SyntaxExpr is like PostTcExpr, but it's filled in a little earlier,
56 -- by the renamer. It's used for rebindable syntax.
57 -- E.g. (>>=) is filled in before the renamer by the appropriate Name
58 -- for (>>=), and then instantiated by the type checker with its
61 type SyntaxExpr id = HsExpr id
63 noSyntaxExpr :: SyntaxExpr id -- Before renaming, and sometimes after,
64 -- (if the syntax slot makes no sense)
65 noSyntaxExpr = HsLit (HsString FSLIT("noSyntaxExpr"))
68 type SyntaxTable id = [(Name, SyntaxExpr id)]
69 -- *** Currently used only for CmdTop (sigh) ***
70 -- * Before the renamer, this list is noSyntaxTable
72 -- * After the renamer, it takes the form [(std_name, HsVar actual_name)]
73 -- For example, for the 'return' op of a monad
74 -- normal case: (GHC.Base.return, HsVar GHC.Base.return)
75 -- with rebindable syntax: (GHC.Base.return, return_22)
76 -- where return_22 is whatever "return" is in scope
78 -- * After the type checker, it takes the form [(std_name, <expression>)]
79 -- where <expression> is the evidence for the method
81 noSyntaxTable :: SyntaxTable id
85 -------------------------
87 = HsVar id -- variable
88 | HsIPVar (IPName id) -- implicit parameter
89 | HsOverLit (HsOverLit id) -- Overloaded literals
90 | HsLit HsLit -- Simple (non-overloaded) literals
92 | HsLam (MatchGroup id) -- Currently always a single match
94 | HsApp (LHsExpr id) -- Application
97 -- Operator applications:
98 -- NB Bracketed ops such as (+) come out as Vars.
100 -- NB We need an expr for the operator in an OpApp/Section since
101 -- the typechecker may need to apply the operator to a few types.
103 | OpApp (LHsExpr id) -- left operand
104 (LHsExpr id) -- operator
105 Fixity -- Renamer adds fixity; bottom until then
106 (LHsExpr id) -- right operand
108 | NegApp (LHsExpr id) -- negated expr
109 (SyntaxExpr id) -- Name of 'negate'
111 | HsPar (LHsExpr id) -- parenthesised expr
113 | SectionL (LHsExpr id) -- operand
114 (LHsExpr id) -- operator
115 | SectionR (LHsExpr id) -- operator
116 (LHsExpr id) -- operand
118 | HsCase (LHsExpr id)
121 | HsIf (LHsExpr id) -- predicate
122 (LHsExpr id) -- then part
123 (LHsExpr id) -- else part
125 | HsLet (HsLocalBinds id) -- let(rec)
128 | HsDo (HsStmtContext Name) -- The parameterisation is unimportant
129 -- because in this context we never use
130 -- the PatGuard or ParStmt variant
131 [LStmt id] -- "do":one or more stmts
132 (LHsExpr id) -- The body; the last expression in the 'do'
133 -- of [ body | ... ] in a list comp
134 PostTcType -- Type of the whole expression
136 | ExplicitList -- syntactic list
137 PostTcType -- Gives type of components of list
140 | ExplicitPArr -- syntactic parallel array: [:e1, ..., en:]
141 PostTcType -- type of elements of the parallel array
144 | ExplicitTuple -- tuple
146 -- NB: Unit is ExplicitTuple []
147 -- for tuples, we can get the types
148 -- direct from the components
152 -- Record construction
153 | RecordCon (Located id) -- The constructor. After type checking
154 -- it's the dataConWrapId of the constructor
155 PostTcExpr -- Data con Id applied to type args
159 | RecordUpd (LHsExpr id)
161 PostTcType -- Type of *input* record
162 PostTcType -- Type of *result* record (may differ from
163 -- type of input record)
165 | ExprWithTySig -- e :: type
169 | ExprWithTySigOut -- TRANSLATION
171 (LHsType Name) -- Retain the signature for round-tripping purposes
173 | ArithSeq -- arithmetic sequence
177 | PArrSeq -- arith. sequence for parallel array
178 PostTcExpr -- [:e1..e2:] or [:e1, e2..e3:]
181 | HsSCC FastString -- "set cost centre" (_scc_) annotation
182 (LHsExpr id) -- expr whose cost is to be measured
184 | HsCoreAnn FastString -- hdaume: core annotation
187 -----------------------------------------------------------
188 -- MetaHaskell Extensions
190 | HsBracket (HsBracket id)
192 | HsBracketOut (HsBracket Name) -- Output of the type checker is the *original*
193 [PendingSplice] -- renamed expression, plus *typechecked* splices
194 -- to be pasted back in by the desugarer
196 | HsSpliceE (HsSplice id)
198 -----------------------------------------------------------
199 -- Arrow notation extension
201 | HsProc (LPat id) -- arrow abstraction, proc
202 (LHsCmdTop id) -- body of the abstraction
203 -- always has an empty stack
205 ---------------------------------------
206 -- The following are commands, not expressions proper
208 | HsArrApp -- Arrow tail, or arrow application (f -< arg)
209 (LHsExpr id) -- arrow expression, f
210 (LHsExpr 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)
217 | HsArrForm -- Command formation, (| e cmd1 .. cmdn |)
218 (LHsExpr id) -- the operator
219 -- after type-checking, a type abstraction to be
220 -- applied to the type of the local environment tuple
221 (Maybe Fixity) -- fixity (filled in by the renamer), for forms that
222 -- were converted from OpApp's by the renamer
223 [LHsCmdTop id] -- argument commands
226 ---------------------------------------
227 -- Haskell program coverage (Hpc) Support
230 Int -- module-local tick number
231 (LHsExpr id) -- sub-expression
234 Int -- module-local tick number for True
235 Int -- module-local tick number for False
236 (LHsExpr id) -- sub-expression
238 | HsTickPragma -- A pragma introduced tick
239 (FastString,(Int,Int),(Int,Int)) -- external span for this tick
242 ---------------------------------------
243 -- These constructors only appear temporarily in the parser.
244 -- The renamer translates them into the Right Thing.
246 | EWildPat -- wildcard
248 | EAsPat (Located id) -- as pattern
251 | ELazyPat (LHsExpr id) -- ~ pattern
253 | HsType (LHsType id) -- Explicit type argument; e.g f {| Int |} x y
255 ---------------------------------------
256 -- Finally, HsWrap appears only in typechecker output
258 | HsWrap HsWrapper -- TRANSLATION
261 type PendingSplice = (Name, LHsExpr Id) -- Typechecked splices, waiting to be
262 -- pasted back in by the desugarer
265 A @Dictionary@, unless of length 0 or 1, becomes a tuple. A
266 @ClassDictLam dictvars methods expr@ is, therefore:
268 \ x -> case x of ( dictvars-and-methods-tuple ) -> expr
272 instance OutputableBndr id => Outputable (HsExpr id) where
273 ppr expr = pprExpr expr
277 pprExpr :: OutputableBndr id => HsExpr id -> SDoc
279 pprExpr e = pprDeeper (ppr_expr e)
281 pprBinds :: OutputableBndr id => HsLocalBinds id -> SDoc
282 pprBinds b = pprDeeper (ppr b)
284 ppr_lexpr :: OutputableBndr id => LHsExpr id -> SDoc
285 ppr_lexpr e = ppr_expr (unLoc e)
287 ppr_expr (HsVar v) = pprHsVar v
288 ppr_expr (HsIPVar v) = ppr v
289 ppr_expr (HsLit lit) = ppr lit
290 ppr_expr (HsOverLit lit) = ppr lit
291 ppr_expr (HsPar e) = parens (ppr_lexpr e)
293 ppr_expr (HsCoreAnn s e)
294 = vcat [ptext SLIT("HsCoreAnn") <+> ftext s, ppr_lexpr e]
296 ppr_expr (HsApp e1 e2)
297 = let (fun, args) = collect_args e1 [e2] in
298 hang (ppr_lexpr fun) 2 (sep (map pprParendExpr args))
300 collect_args (L _ (HsApp fun arg)) args = collect_args fun (arg:args)
301 collect_args fun args = (fun, args)
303 ppr_expr (OpApp e1 op fixity e2)
305 HsVar v -> pp_infixly v
308 pp_e1 = pprParendExpr e1 -- Add parens to make precedence clear
309 pp_e2 = pprParendExpr e2
312 = hang (ppr op) 2 (sep [pp_e1, pp_e2])
315 = sep [nest 2 pp_e1, pprInfix v, nest 2 pp_e2]
317 ppr_expr (NegApp e _) = char '-' <+> pprParendExpr e
319 ppr_expr (SectionL expr op)
321 HsVar v -> pp_infixly v
324 pp_expr = pprParendExpr expr
326 pp_prefixly = hang (hsep [text " \\ x_ ->", ppr op])
327 4 (hsep [pp_expr, ptext SLIT("x_ )")])
328 pp_infixly v = parens (sep [pp_expr, pprInfix v])
330 ppr_expr (SectionR op expr)
332 HsVar v -> pp_infixly v
335 pp_expr = pprParendExpr expr
337 pp_prefixly = hang (hsep [text "( \\ x_ ->", ppr op, ptext SLIT("x_")])
338 4 ((<>) pp_expr rparen)
340 = parens (sep [pprInfix v, pp_expr])
342 ppr_expr (HsLam matches)
343 = pprMatches LambdaExpr matches
345 ppr_expr (HsCase expr matches)
346 = sep [ sep [ptext SLIT("case"), nest 4 (ppr expr), ptext SLIT("of")],
347 nest 2 (pprMatches CaseAlt matches) ]
349 ppr_expr (HsIf e1 e2 e3)
350 = sep [hsep [ptext SLIT("if"), nest 2 (ppr e1), ptext SLIT("then")],
355 -- special case: let ... in let ...
356 ppr_expr (HsLet binds expr@(L _ (HsLet _ _)))
357 = sep [hang (ptext SLIT("let")) 2 (hsep [pprBinds binds, ptext SLIT("in")]),
360 ppr_expr (HsLet binds expr)
361 = sep [hang (ptext SLIT("let")) 2 (pprBinds binds),
362 hang (ptext SLIT("in")) 2 (ppr expr)]
364 ppr_expr (HsDo do_or_list_comp stmts body _) = pprDo do_or_list_comp stmts body
366 ppr_expr (ExplicitList _ exprs)
367 = brackets (fsep (punctuate comma (map ppr_lexpr exprs)))
369 ppr_expr (ExplicitPArr _ exprs)
370 = pa_brackets (fsep (punctuate comma (map ppr_lexpr exprs)))
372 ppr_expr (ExplicitTuple exprs boxity)
373 = tupleParens boxity (sep (punctuate comma (map ppr_lexpr exprs)))
375 ppr_expr (RecordCon con_id con_expr rbinds)
376 = pp_rbinds (ppr con_id) rbinds
378 ppr_expr (RecordUpd aexp rbinds _ _)
379 = pp_rbinds (pprParendExpr aexp) rbinds
381 ppr_expr (ExprWithTySig expr sig)
382 = hang (nest 2 (ppr_lexpr expr) <+> dcolon)
384 ppr_expr (ExprWithTySigOut expr sig)
385 = hang (nest 2 (ppr_lexpr expr) <+> dcolon)
388 ppr_expr (ArithSeq expr info) = brackets (ppr info)
389 ppr_expr (PArrSeq expr info) = pa_brackets (ppr info)
391 ppr_expr EWildPat = char '_'
392 ppr_expr (ELazyPat e) = char '~' <> pprParendExpr e
393 ppr_expr (EAsPat v e) = ppr v <> char '@' <> pprParendExpr e
395 ppr_expr (HsSCC lbl expr)
396 = sep [ ptext SLIT("_scc_") <+> doubleQuotes (ftext lbl), pprParendExpr expr ]
398 ppr_expr (HsWrap co_fn e) = pprHsWrapper (ppr_expr e) co_fn
399 ppr_expr (HsType id) = ppr id
401 ppr_expr (HsSpliceE s) = pprSplice s
402 ppr_expr (HsBracket b) = pprHsBracket b
403 ppr_expr (HsBracketOut e []) = ppr e
404 ppr_expr (HsBracketOut e ps) = ppr e $$ ptext SLIT("pending") <+> ppr ps
406 ppr_expr (HsProc pat (L _ (HsCmdTop cmd _ _ _)))
407 = hsep [ptext SLIT("proc"), ppr pat, ptext SLIT("->"), ppr cmd]
409 ppr_expr (HsTick tickId exp)
410 = hcat [ptext SLIT("tick<"), ppr tickId,ptext SLIT(">("), ppr exp,ptext SLIT(")")]
411 ppr_expr (HsBinTick tickIdTrue tickIdFalse exp)
412 = hcat [ptext SLIT("bintick<"),
417 ppr exp,ptext SLIT(")")]
418 ppr_expr (HsTickPragma externalSrcLoc exp)
419 = hcat [ptext SLIT("tickpragma<"), ppr externalSrcLoc,ptext SLIT(">("), ppr exp,ptext SLIT(")")]
421 ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp True)
422 = hsep [ppr_lexpr arrow, ptext SLIT("-<"), ppr_lexpr arg]
423 ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp False)
424 = hsep [ppr_lexpr arg, ptext SLIT(">-"), ppr_lexpr arrow]
425 ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp True)
426 = hsep [ppr_lexpr arrow, ptext SLIT("-<<"), ppr_lexpr arg]
427 ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp False)
428 = hsep [ppr_lexpr arg, ptext SLIT(">>-"), ppr_lexpr arrow]
430 ppr_expr (HsArrForm (L _ (HsVar v)) (Just _) [arg1, arg2])
431 = sep [pprCmdArg (unLoc arg1), hsep [pprInfix v, pprCmdArg (unLoc arg2)]]
432 ppr_expr (HsArrForm op _ args)
433 = hang (ptext SLIT("(|") <> ppr_lexpr op)
434 4 (sep (map (pprCmdArg.unLoc) args) <> ptext SLIT("|)"))
436 pprCmdArg :: OutputableBndr id => HsCmdTop id -> SDoc
437 pprCmdArg (HsCmdTop cmd@(L _ (HsArrForm _ Nothing [])) _ _ _)
439 pprCmdArg (HsCmdTop cmd _ _ _)
440 = parens (ppr_lexpr cmd)
442 -- Put a var in backquotes if it's not an operator already
443 pprInfix :: Outputable name => name -> SDoc
444 pprInfix v | isOperator ppr_v = ppr_v
445 | otherwise = char '`' <> ppr_v <> char '`'
449 -- add parallel array brackets around a document
451 pa_brackets :: SDoc -> SDoc
452 pa_brackets p = ptext SLIT("[:") <> p <> ptext SLIT(":]")
455 Parenthesize unless very simple:
457 pprParendExpr :: OutputableBndr id => LHsExpr id -> SDoc
460 pp_as_was = ppr_lexpr expr
461 -- Using ppr_expr here avoids the call to 'deeper'
462 -- Not sure if that's always right.
469 HsIPVar _ -> pp_as_was
470 ExplicitList _ _ -> pp_as_was
471 ExplicitPArr _ _ -> pp_as_was
472 ExplicitTuple _ _ -> pp_as_was
474 HsBracket _ -> pp_as_was
475 HsBracketOut _ [] -> pp_as_was
477 _ -> parens pp_as_was
480 %************************************************************************
482 \subsection{Commands (in arrow abstractions)}
484 %************************************************************************
486 We re-use HsExpr to represent these.
489 type HsCmd id = HsExpr id
491 type LHsCmd id = LHsExpr id
493 data HsArrAppType = HsHigherOrderApp | HsFirstOrderApp
496 The legal constructors for commands are:
498 = HsArrApp ... -- as above
500 | HsArrForm ... -- as above
505 | HsLam (Match id) -- kappa
507 -- the renamer turns this one into HsArrForm
508 | OpApp (HsExpr id) -- left operand
509 (HsCmd id) -- operator
510 Fixity -- Renamer adds fixity; bottom until then
511 (HsCmd id) -- right operand
513 | HsPar (HsCmd id) -- parenthesised command
516 [Match id] -- bodies are HsCmd's
519 | HsIf (HsExpr id) -- predicate
520 (HsCmd id) -- then part
521 (HsCmd id) -- else part
524 | HsLet (HsLocalBinds id) -- let(rec)
527 | HsDo (HsStmtContext Name) -- The parameterisation is unimportant
528 -- because in this context we never use
529 -- the PatGuard or ParStmt variant
530 [Stmt id] -- HsExpr's are really HsCmd's
531 PostTcType -- Type of the whole expression
534 Top-level command, introducing a new arrow.
535 This may occur inside a proc (where the stack is empty) or as an
536 argument of a command-forming operator.
539 type LHsCmdTop id = Located (HsCmdTop id)
542 = HsCmdTop (LHsCmd id)
543 [PostTcType] -- types of inputs on the command's stack
544 PostTcType -- return type of the command
546 -- after type checking:
547 -- names used in the command's desugaring
550 %************************************************************************
552 \subsection{Record binds}
554 %************************************************************************
557 data HsRecordBinds id = HsRecordBinds [(Located id, LHsExpr id)]
559 recBindFields :: HsRecordBinds id -> [id]
560 recBindFields (HsRecordBinds rbinds) = [unLoc field | (field,_) <- rbinds]
562 pp_rbinds :: OutputableBndr id => SDoc -> HsRecordBinds id -> SDoc
563 pp_rbinds thing (HsRecordBinds rbinds)
565 4 (braces (sep (punctuate comma (map (pp_rbind) rbinds))))
567 pp_rbind (v, e) = hsep [pprBndr LetBind (unLoc v), char '=', ppr e]
572 %************************************************************************
574 \subsection{@Match@, @GRHSs@, and @GRHS@ datatypes}
576 %************************************************************************
578 @Match@es are sets of pattern bindings and right hand sides for
579 functions, patterns or case branches. For example, if a function @g@
585 then \tr{g} has two @Match@es: @(x,y) = y@ and @((x:ys),y) = y+1@.
587 It is always the case that each element of an @[Match]@ list has the
588 same number of @pats@s inside it. This corresponds to saying that
589 a function defined by pattern matching must have the same number of
590 patterns in each equation.
595 [LMatch id] -- The alternatives
596 PostTcType -- The type is the type of the entire group
597 -- t1 -> ... -> tn -> tr
598 -- where there are n patterns
600 type LMatch id = Located (Match id)
604 [LPat id] -- The patterns
605 (Maybe (LHsType id)) -- A type signature for the result of the match
606 -- Nothing after typechecking
609 matchGroupArity :: MatchGroup id -> Arity
610 matchGroupArity (MatchGroup [] _)
611 = panic "matchGroupArity" -- MatchGroup is never empty
612 matchGroupArity (MatchGroup (match:matches) _)
613 = ASSERT( all ((== n_pats) . length . hsLMatchPats) matches )
614 -- Assertion just checks that all the matches have the same number of pats
617 n_pats = length (hsLMatchPats match)
619 hsLMatchPats :: LMatch id -> [LPat id]
620 hsLMatchPats (L _ (Match pats _ _)) = pats
622 -- GRHSs are used both for pattern bindings and for Matches
624 = GRHSs [LGRHS id] -- Guarded RHSs
625 (HsLocalBinds id) -- The where clause
627 type LGRHS id = Located (GRHS id)
629 data GRHS id = GRHS [LStmt id] -- Guards
630 (LHsExpr id) -- Right hand side
633 We know the list must have at least one @Match@ in it.
636 pprMatches :: (OutputableBndr id) => HsMatchContext id -> MatchGroup id -> SDoc
637 pprMatches ctxt (MatchGroup matches ty) = vcat (map (pprMatch ctxt) (map unLoc matches))
638 -- Don't print the type; it's only
639 -- a place-holder before typechecking
641 -- Exported to HsBinds, which can't see the defn of HsMatchContext
642 pprFunBind :: (OutputableBndr id) => id -> MatchGroup id -> SDoc
643 pprFunBind fun matches = pprMatches (FunRhs fun) matches
645 -- Exported to HsBinds, which can't see the defn of HsMatchContext
646 pprPatBind :: (OutputableBndr bndr, OutputableBndr id)
647 => LPat bndr -> GRHSs id -> SDoc
648 pprPatBind pat grhss = sep [ppr pat, nest 4 (pprGRHSs PatBindRhs grhss)]
651 pprMatch :: OutputableBndr id => HsMatchContext id -> Match id -> SDoc
652 pprMatch ctxt (Match pats maybe_ty grhss)
653 = pp_name ctxt <+> sep [sep (map ppr pats),
655 nest 2 (pprGRHSs ctxt grhss)]
657 pp_name (FunRhs fun) = ppr fun -- Not pprBndr; the AbsBinds will
658 -- have printed the signature
659 pp_name LambdaExpr = char '\\'
660 pp_name other = empty
662 ppr_maybe_ty = case maybe_ty of
663 Just ty -> dcolon <+> ppr ty
667 pprGRHSs :: OutputableBndr id => HsMatchContext id -> GRHSs id -> SDoc
668 pprGRHSs ctxt (GRHSs grhss binds)
669 = vcat (map (pprGRHS ctxt . unLoc) grhss)
671 (if isEmptyLocalBinds binds then empty
672 else text "where" $$ nest 4 (pprBinds binds))
674 pprGRHS :: OutputableBndr id => HsMatchContext id -> GRHS id -> SDoc
676 pprGRHS ctxt (GRHS [] expr)
679 pprGRHS ctxt (GRHS guards expr)
680 = sep [char '|' <+> interpp'SP guards, pp_rhs ctxt expr]
682 pp_rhs ctxt rhs = matchSeparator ctxt <+> pprDeeper (ppr rhs)
685 %************************************************************************
687 \subsection{Do stmts and list comprehensions}
689 %************************************************************************
692 type LStmt id = Located (Stmt id)
694 -- The SyntaxExprs in here are used *only* for do-notation, which
695 -- has rebindable syntax. Otherwise they are unused.
699 (SyntaxExpr id) -- The (>>=) operator
700 (SyntaxExpr id) -- The fail operator
701 -- The fail operator is noSyntaxExpr
702 -- if the pattern match can't fail
704 | ExprStmt (LHsExpr id)
705 (SyntaxExpr id) -- The (>>) operator
706 PostTcType -- Element type of the RHS (used for arrows)
708 | LetStmt (HsLocalBinds id)
710 -- ParStmts only occur in a list comprehension
711 | ParStmt [([LStmt id], [id])] -- After renaming, the ids are the binders
712 -- bound by the stmts and used subsequently
714 -- Recursive statement (see Note [RecStmt] below)
716 --- The next two fields are only valid after renaming
717 [id] -- The ids are a subset of the variables bound by the stmts
718 -- that are used in stmts that follow the RecStmt
720 [id] -- Ditto, but these variables are the "recursive" ones, that
721 -- are used before they are bound in the stmts of the RecStmt
722 -- From a type-checking point of view, these ones have to be monomorphic
724 --- These fields are only valid after typechecking
725 [PostTcExpr] -- These expressions correspond
726 -- 1-to-1 with the "recursive" [id], and are the expresions that
727 -- should be returned by the recursion. They may not quite be the
728 -- Ids themselves, because the Id may be *polymorphic*, but
729 -- the returned thing has to be *monomorphic*.
730 (DictBinds id) -- Method bindings of Ids bound by the RecStmt,
731 -- and used afterwards
734 ExprStmts are a bit tricky, because what they mean
735 depends on the context. Consider the following contexts:
737 A do expression of type (m res_ty)
738 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
739 * ExprStmt E any_ty: do { ....; E; ... }
741 Translation: E >> ...
743 A list comprehensions of type [elt_ty]
744 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
745 * ExprStmt E Bool: [ .. | .... E ]
747 [ .. | .... | ..., E | ... ]
749 Translation: if E then fail else ...
751 A guard list, guarding a RHS of type rhs_ty
752 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
753 * ExprStmt E Bool: f x | ..., E, ... = ...rhs...
755 Translation: if E then fail else ...
757 Array comprehensions are handled like list comprehensions -=chak
764 , RecStmt [a::forall a. a -> a, b]
766 [ BindStmt b (return x)
772 Here, the RecStmt binds a,b,c; but
773 - Only a,b are used in the stmts *following* the RecStmt,
774 This 'a' is *polymorphic'
775 - Only a,c are used in the stmts *inside* the RecStmt
776 *before* their bindings
777 This 'a' is monomorphic
779 Nota Bene: the two a's have different types, even though they
784 instance OutputableBndr id => Outputable (Stmt id) where
785 ppr stmt = pprStmt stmt
787 pprStmt (BindStmt pat expr _ _) = hsep [ppr pat, ptext SLIT("<-"), ppr expr]
788 pprStmt (LetStmt binds) = hsep [ptext SLIT("let"), pprBinds binds]
789 pprStmt (ExprStmt 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 -> [LStmt id] -> LHsExpr id -> SDoc
794 pprDo DoExpr stmts body = ptext SLIT("do") <+> (vcat (map ppr stmts) $$ ppr body)
795 pprDo (MDoExpr _) stmts body = ptext SLIT("mdo") <+> (vcat (map ppr stmts) $$ ppr body)
796 pprDo ListComp stmts body = pprComp brackets stmts body
797 pprDo PArrComp stmts body = pprComp pa_brackets stmts body
798 pprDo other stmts body = panic "pprDo" -- PatGuard, ParStmtCxt
800 pprComp :: OutputableBndr id => (SDoc -> SDoc) -> [LStmt id] -> LHsExpr id -> SDoc
801 pprComp brack quals body
803 hang (ppr body <+> char '|')
807 %************************************************************************
809 Template Haskell quotation brackets
811 %************************************************************************
814 data HsSplice id = HsSplice -- $z or $(f 4)
815 id -- The id is just a unique name to
816 (LHsExpr id) -- identify this splice point
818 instance OutputableBndr id => Outputable (HsSplice id) where
821 pprSplice :: OutputableBndr id => HsSplice id -> SDoc
822 pprSplice (HsSplice n e) = char '$' <> brackets (ppr n) <> pprParendExpr e
825 data HsBracket id = ExpBr (LHsExpr id) -- [| expr |]
826 | PatBr (LPat id) -- [p| pat |]
827 | DecBr (HsGroup id) -- [d| decls |]
828 | TypBr (LHsType id) -- [t| type |]
829 | VarBr id -- 'x, ''T
831 instance OutputableBndr id => Outputable (HsBracket id) where
835 pprHsBracket (ExpBr e) = thBrackets empty (ppr e)
836 pprHsBracket (PatBr p) = thBrackets (char 'p') (ppr p)
837 pprHsBracket (DecBr d) = thBrackets (char 'd') (ppr d)
838 pprHsBracket (TypBr t) = thBrackets (char 't') (ppr t)
839 pprHsBracket (VarBr n) = char '\'' <> ppr n
840 -- Infelicity: can't show ' vs '', because
841 -- we can't ask n what its OccName is, because the
842 -- pretty-printer for HsExpr doesn't ask for NamedThings
843 -- But the pretty-printer for names will show the OccName class
845 thBrackets pp_kind pp_body = char '[' <> pp_kind <> char '|' <+>
846 pp_body <+> ptext SLIT("|]")
849 %************************************************************************
851 \subsection{Enumerations and list comprehensions}
853 %************************************************************************
858 | FromThen (LHsExpr id)
860 | FromTo (LHsExpr id)
862 | FromThenTo (LHsExpr id)
868 instance OutputableBndr id => Outputable (ArithSeqInfo id) where
869 ppr (From e1) = hcat [ppr e1, pp_dotdot]
870 ppr (FromThen e1 e2) = hcat [ppr e1, comma, space, ppr e2, pp_dotdot]
871 ppr (FromTo e1 e3) = hcat [ppr e1, pp_dotdot, ppr e3]
872 ppr (FromThenTo e1 e2 e3)
873 = hcat [ppr e1, comma, space, ppr e2, pp_dotdot, ppr e3]
875 pp_dotdot = ptext SLIT(" .. ")
879 %************************************************************************
881 \subsection{HsMatchCtxt}
883 %************************************************************************
886 data HsMatchContext id -- Context of a Match
887 = FunRhs id -- Function binding for f
888 | CaseAlt -- Guard on a case alternative
889 | LambdaExpr -- Pattern of a lambda
890 | ProcExpr -- Pattern of a proc
891 | PatBindRhs -- Pattern binding
892 | RecUpd -- Record update [used only in DsExpr to tell matchWrapper
893 -- what sort of runtime error message to generate]
894 | StmtCtxt (HsStmtContext id) -- Pattern of a do-stmt or list comprehension
897 data HsStmtContext id
900 | MDoExpr PostTcTable -- Recursive do-expression
901 -- (tiresomely, it needs table
902 -- of its return/bind ops)
903 | PArrComp -- Parallel array comprehension
904 | PatGuard (HsMatchContext id) -- Pattern guard for specified thing
905 | ParStmtCtxt (HsStmtContext id) -- A branch of a parallel stmt
909 isDoExpr :: HsStmtContext id -> Bool
910 isDoExpr DoExpr = True
911 isDoExpr (MDoExpr _) = True
912 isDoExpr other = False
916 matchSeparator (FunRhs _) = ptext SLIT("=")
917 matchSeparator CaseAlt = ptext SLIT("->")
918 matchSeparator LambdaExpr = ptext SLIT("->")
919 matchSeparator ProcExpr = ptext SLIT("->")
920 matchSeparator PatBindRhs = ptext SLIT("=")
921 matchSeparator (StmtCtxt _) = ptext SLIT("<-")
922 matchSeparator RecUpd = panic "unused"
926 pprMatchContext (FunRhs fun) = ptext SLIT("the definition of") <+> quotes (ppr fun)
927 pprMatchContext CaseAlt = ptext SLIT("a case alternative")
928 pprMatchContext RecUpd = ptext SLIT("a record-update construct")
929 pprMatchContext PatBindRhs = ptext SLIT("a pattern binding")
930 pprMatchContext LambdaExpr = ptext SLIT("a lambda abstraction")
931 pprMatchContext ProcExpr = ptext SLIT("an arrow abstraction")
932 pprMatchContext (StmtCtxt ctxt) = ptext SLIT("a pattern binding in") $$ pprStmtContext ctxt
934 pprStmtContext (ParStmtCtxt c) = sep [ptext SLIT("a parallel branch of"), pprStmtContext c]
935 pprStmtContext (PatGuard ctxt) = ptext SLIT("a pattern guard for") $$ pprMatchContext ctxt
936 pprStmtContext DoExpr = ptext SLIT("a 'do' expression")
937 pprStmtContext (MDoExpr _) = ptext SLIT("an 'mdo' expression")
938 pprStmtContext ListComp = ptext SLIT("a list comprehension")
939 pprStmtContext PArrComp = ptext SLIT("an array comprehension")
942 pprMatchRhsContext (FunRhs fun) = ptext SLIT("a right-hand side of function") <+> quotes (ppr fun)
943 pprMatchRhsContext CaseAlt = ptext SLIT("the body of a case alternative")
944 pprMatchRhsContext PatBindRhs = ptext SLIT("the right-hand side of a pattern binding")
945 pprMatchRhsContext LambdaExpr = ptext SLIT("the body of a lambda")
946 pprMatchRhsContext ProcExpr = ptext SLIT("the body of a proc")
947 pprMatchRhsContext other = panic "pprMatchRhsContext" -- RecUpd, StmtCtxt
949 -- Used for the result statement of comprehension
950 -- e.g. the 'e' in [ e | ... ]
951 -- or the 'r' in f x = r
952 pprStmtResultContext (PatGuard ctxt) = pprMatchRhsContext ctxt
953 pprStmtResultContext other = ptext SLIT("the result of") <+> pprStmtContext other
956 -- Used to generate the string for a *runtime* error message
957 matchContextErrString (FunRhs fun) = "function " ++ showSDoc (ppr fun)
958 matchContextErrString CaseAlt = "case"
959 matchContextErrString PatBindRhs = "pattern binding"
960 matchContextErrString RecUpd = "record update"
961 matchContextErrString LambdaExpr = "lambda"
962 matchContextErrString ProcExpr = "proc"
963 matchContextErrString (StmtCtxt (ParStmtCtxt c)) = matchContextErrString (StmtCtxt c)
964 matchContextErrString (StmtCtxt (PatGuard _)) = "pattern guard"
965 matchContextErrString (StmtCtxt DoExpr) = "'do' expression"
966 matchContextErrString (StmtCtxt (MDoExpr _)) = "'mdo' expression"
967 matchContextErrString (StmtCtxt ListComp) = "list comprehension"
968 matchContextErrString (StmtCtxt PArrComp) = "array comprehension"