2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[HsExpr]{Abstract Haskell syntax: expressions}
9 #include "HsVersions.h"
12 import HsBinds ( HsBinds(..), nullBinds )
13 import HsTypes ( PostTcType )
14 import HsLit ( HsLit, HsOverLit )
15 import BasicTypes ( Fixity(..) )
16 import HsTypes ( HsType )
17 import HsImpExp ( isOperator )
21 import ForeignCall ( Safety )
23 import PprType ( pprParendType )
26 import DataCon ( DataCon )
27 import CStrings ( CLabelString, pprCLabelString )
28 import BasicTypes ( IPName, Boxity, tupleParens )
29 import SrcLoc ( SrcLoc )
32 %************************************************************************
34 \subsection{Expressions proper}
36 %************************************************************************
40 = HsVar id -- variable
41 | HsIPVar (IPName id) -- implicit parameter
42 | HsOverLit HsOverLit -- Overloaded literals; eliminated by type checker
43 | HsLit HsLit -- Simple (non-overloaded) literals
45 | HsLam (Match id pat) -- lambda
46 | HsApp (HsExpr id pat) -- application
49 -- Operator applications:
50 -- NB Bracketed ops such as (+) come out as Vars.
52 -- NB We need an expr for the operator in an OpApp/Section since
53 -- the typechecker may need to apply the operator to a few types.
55 | OpApp (HsExpr id pat) -- left operand
56 (HsExpr id pat) -- operator
57 Fixity -- Renamer adds fixity; bottom until then
58 (HsExpr id pat) -- right operand
60 -- We preserve prefix negation and parenthesis for the precedence parser.
61 -- They are eventually removed by the type checker.
63 | NegApp (HsExpr id pat) -- negated expr
64 Name -- Name of 'negate' (see RnEnv.lookupSyntaxName)
66 | HsPar (HsExpr id pat) -- parenthesised expr
68 | SectionL (HsExpr id pat) -- operand
69 (HsExpr id pat) -- operator
70 | SectionR (HsExpr id pat) -- operator
71 (HsExpr id pat) -- operand
73 | HsCase (HsExpr id pat)
77 | HsIf (HsExpr id pat) -- predicate
78 (HsExpr id pat) -- then part
79 (HsExpr id pat) -- else part
82 | HsLet (HsBinds id pat) -- let(rec)
85 | HsWith (HsExpr id pat) -- implicit parameter binding
86 [(IPName id, HsExpr id pat)]
87 Bool -- True <=> this was a 'with' binding
88 -- (tmp, until 'with' is removed)
91 [Stmt id pat] -- "do":one or more stmts
95 [Stmt id pat] -- "do":one or more stmts
96 [id] -- ids for [return,fail,>>=,>>]
98 Type -- Type of the whole expression
101 | ExplicitList -- syntactic list
102 PostTcType -- Gives type of components of list
105 | ExplicitPArr -- syntactic parallel array: [:e1, ..., en:]
106 PostTcType -- type of elements of the parallel array
109 | ExplicitTuple -- tuple
111 -- NB: Unit is ExplicitTuple []
112 -- for tuples, we can get the types
113 -- direct from the components
117 -- Record construction
118 | RecordCon id -- The constructor
119 (HsRecordBinds id pat)
121 | RecordConOut DataCon
122 (HsExpr id pat) -- Data con Id applied to type args
123 (HsRecordBinds id pat)
127 | RecordUpd (HsExpr id pat)
128 (HsRecordBinds id pat)
130 | RecordUpdOut (HsExpr id pat) -- TRANSLATION
131 Type -- Type of *input* record
132 Type -- Type of *result* record (may differ from
133 -- type of input record)
134 (HsRecordBinds id pat)
136 | ExprWithTySig -- signature binding
139 | ArithSeqIn -- arithmetic sequence
140 (ArithSeqInfo id pat)
142 (HsExpr id pat) -- (typechecked, of course)
143 (ArithSeqInfo id pat)
144 | PArrSeqIn -- arith. sequence for parallel array
145 (ArithSeqInfo id pat) -- [:e1..e2:] or [:e1, e2..e3:]
147 (HsExpr id pat) -- (typechecked, of course)
148 (ArithSeqInfo id pat)
150 | HsCCall CLabelString -- call into the C world; string is
151 [HsExpr id pat] -- the C function; exprs are the
152 -- arguments to pass.
153 Safety -- True <=> might cause Haskell
154 -- garbage-collection (must generate
155 -- more paranoid code)
156 Bool -- True <=> it's really a "casm"
157 -- NOTE: this CCall is the *boxed*
158 -- version; the desugarer will convert
159 -- it into the unboxed "ccall#".
160 PostTcType -- The result type; will be *bottom*
161 -- until the typechecker gets ahold of it
163 | HsSCC FAST_STRING -- "set cost centre" (_scc_) annotation
164 (HsExpr id pat) -- expr whose cost is to be measured
168 These constructors only appear temporarily in the parser.
169 The renamer translates them into the Right Thing.
172 | EWildPat -- wildcard
174 | EAsPat id -- as pattern
177 | ELazyPat (HsExpr id pat) -- ~ pattern
179 | HsType (HsType id) -- Explicit type argument; e.g f {| Int |} x y
182 Everything from here on appears only in typechecker output.
185 | TyLam -- TRANSLATION
188 | TyApp -- TRANSLATION
189 (HsExpr id pat) -- generated by Spec
192 -- DictLam and DictApp are "inverses"
200 type HsRecordBinds id pat
201 = [(id, HsExpr id pat, Bool)]
202 -- True <=> source code used "punning",
203 -- i.e. {op1, op2} rather than {op1=e1, op2=e2}
206 A @Dictionary@, unless of length 0 or 1, becomes a tuple. A
207 @ClassDictLam dictvars methods expr@ is, therefore:
209 \ x -> case x of ( dictvars-and-methods-tuple ) -> expr
213 instance (Outputable id, Outputable pat) =>
214 Outputable (HsExpr id pat) where
215 ppr expr = pprExpr expr
219 pprExpr :: (Outputable id, Outputable pat)
220 => HsExpr id pat -> SDoc
222 pprExpr e = pprDeeper (ppr_expr e)
223 pprBinds b = pprDeeper (ppr b)
226 -- Put it in parens if it's an operator
227 | isOperator v = parens (ppr v)
230 ppr_expr (HsIPVar v) = ppr v
231 ppr_expr (HsLit lit) = ppr lit
232 ppr_expr (HsOverLit lit) = ppr lit
234 ppr_expr (HsLam match)
235 = hsep [char '\\', nest 2 (pprMatch LambdaExpr match)]
237 ppr_expr expr@(HsApp e1 e2)
238 = let (fun, args) = collect_args expr [] in
239 (ppr_expr fun) <+> (sep (map ppr_expr args))
241 collect_args (HsApp fun arg) args = collect_args fun (arg:args)
242 collect_args fun args = (fun, args)
244 ppr_expr (OpApp e1 op fixity e2)
246 HsVar v -> pp_infixly v
249 pp_e1 = pprParendExpr e1 -- Add parens to make precedence clear
250 pp_e2 = pprParendExpr e2
253 = hang (pprExpr op) 4 (sep [pp_e1, pp_e2])
256 = sep [pp_e1, hsep [pp_v_op, pp_e2]]
258 pp_v_op | isOperator v = ppr v
259 | otherwise = char '`' <> ppr v <> char '`'
260 -- Put it in backquotes if it's not an operator already
262 ppr_expr (NegApp e _) = char '-' <+> pprParendExpr e
264 ppr_expr (HsPar e) = parens (ppr_expr e)
266 ppr_expr (SectionL expr op)
268 HsVar v -> pp_infixly v
271 pp_expr = pprParendExpr expr
273 pp_prefixly = hang (hsep [text " \\ x_ ->", ppr op])
274 4 (hsep [pp_expr, ptext SLIT("x_ )")])
275 pp_infixly v = parens (sep [pp_expr, ppr v])
277 ppr_expr (SectionR op expr)
279 HsVar v -> pp_infixly v
282 pp_expr = pprParendExpr expr
284 pp_prefixly = hang (hsep [text "( \\ x_ ->", ppr op, ptext SLIT("x_")])
285 4 ((<>) pp_expr rparen)
287 = parens (sep [ppr v, pp_expr])
289 ppr_expr (HsCase expr matches _)
290 = sep [ sep [ptext SLIT("case"), nest 4 (pprExpr expr), ptext SLIT("of")],
291 nest 2 (pprMatches CaseAlt matches) ]
293 ppr_expr (HsIf e1 e2 e3 _)
294 = sep [hsep [ptext SLIT("if"), nest 2 (pprExpr e1), ptext SLIT("then")],
299 -- special case: let ... in let ...
300 ppr_expr (HsLet binds expr@(HsLet _ _))
301 = sep [hang (ptext SLIT("let")) 2 (hsep [pprBinds binds, ptext SLIT("in")]),
304 ppr_expr (HsLet binds expr)
305 = sep [hang (ptext SLIT("let")) 2 (pprBinds binds),
306 hang (ptext SLIT("in")) 2 (ppr expr)]
308 ppr_expr (HsWith expr binds is_with)
309 = sep [hang (ptext SLIT("let")) 2 (pp_ipbinds binds),
310 hang (ptext SLIT("in")) 2 (ppr expr)]
312 ppr_expr (HsDo do_or_list_comp stmts _) = pprDo do_or_list_comp stmts
313 ppr_expr (HsDoOut do_or_list_comp stmts _ _ _) = pprDo do_or_list_comp stmts
315 ppr_expr (ExplicitList _ exprs)
316 = brackets (fsep (punctuate comma (map ppr_expr exprs)))
318 ppr_expr (ExplicitPArr _ exprs)
319 = pabrackets (fsep (punctuate comma (map ppr_expr exprs)))
321 ppr_expr (ExplicitTuple exprs boxity)
322 = tupleParens boxity (sep (punctuate comma (map ppr_expr exprs)))
324 ppr_expr (RecordCon con_id rbinds)
325 = pp_rbinds (ppr con_id) rbinds
326 ppr_expr (RecordConOut data_con con rbinds)
327 = pp_rbinds (ppr con) rbinds
329 ppr_expr (RecordUpd aexp rbinds)
330 = pp_rbinds (pprParendExpr aexp) rbinds
331 ppr_expr (RecordUpdOut aexp _ _ rbinds)
332 = pp_rbinds (pprParendExpr aexp) rbinds
334 ppr_expr (ExprWithTySig expr sig)
335 = hang (nest 2 (ppr_expr expr) <+> dcolon)
338 ppr_expr (ArithSeqIn info)
339 = brackets (ppr info)
340 ppr_expr (ArithSeqOut expr info)
341 = brackets (ppr info)
343 ppr_expr (PArrSeqIn info)
344 = pabrackets (ppr info)
345 ppr_expr (PArrSeqOut expr info)
346 = pabrackets (ppr info)
348 ppr_expr EWildPat = char '_'
349 ppr_expr (ELazyPat e) = char '~' <> pprParendExpr e
350 ppr_expr (EAsPat v e) = ppr v <> char '@' <> pprParendExpr e
352 ppr_expr (HsCCall fun args _ is_asm result_ty)
354 then ptext SLIT("_casm_ ``") <> pprCLabelString fun <> ptext SLIT("''")
355 else ptext SLIT("_ccall_") <+> pprCLabelString fun)
356 4 (sep (map pprParendExpr args))
358 ppr_expr (HsSCC lbl expr)
359 = sep [ ptext SLIT("_scc_") <+> doubleQuotes (ptext lbl), pprParendExpr expr ]
361 ppr_expr (TyLam tyvars expr)
362 = hang (hsep [ptext SLIT("/\\"), interppSP tyvars, ptext SLIT("->")])
365 ppr_expr (TyApp expr [ty])
366 = hang (ppr_expr expr) 4 (pprParendType ty)
368 ppr_expr (TyApp expr tys)
369 = hang (ppr_expr expr)
370 4 (brackets (interpp'SP tys))
372 ppr_expr (DictLam dictvars expr)
373 = hang (hsep [ptext SLIT("\\{-dict-}"), interppSP dictvars, ptext SLIT("->")])
376 ppr_expr (DictApp expr [dname])
377 = hang (ppr_expr expr) 4 (ppr dname)
379 ppr_expr (DictApp expr dnames)
380 = hang (ppr_expr expr)
381 4 (brackets (interpp'SP dnames))
383 ppr_expr (HsType id) = ppr id
385 -- add parallel array brackets around a document
387 pabrackets :: SDoc -> SDoc
388 pabrackets p = ptext SLIT("[:") <> p <> ptext SLIT(":]")
391 Parenthesize unless very simple:
393 pprParendExpr :: (Outputable id, Outputable pat)
394 => HsExpr id pat -> SDoc
398 pp_as_was = pprExpr expr
405 HsIPVar _ -> pp_as_was
406 ExplicitList _ _ -> pp_as_was
407 ExplicitPArr _ _ -> pp_as_was
408 ExplicitTuple _ _ -> pp_as_was
411 _ -> parens pp_as_was
414 %************************************************************************
416 \subsection{Record binds}
418 %************************************************************************
421 pp_rbinds :: (Outputable id, Outputable pat)
423 -> HsRecordBinds id pat -> SDoc
425 pp_rbinds thing rbinds
427 4 (braces (sep (punctuate comma (map (pp_rbind) rbinds))))
429 pp_rbind (v, e, pun_flag)
430 = getPprStyle $ \ sty ->
431 if pun_flag && userStyle sty then
434 hsep [ppr v, char '=', ppr e]
438 pp_ipbinds :: (Outputable id, Outputable pat)
439 => [(IPName id, HsExpr id pat)] -> SDoc
440 pp_ipbinds pairs = hsep (punctuate semi (map pp_item pairs))
442 pp_item (id,rhs) = ppr id <+> equals <+> ppr_expr rhs
446 %************************************************************************
448 \subsection{@Match@, @GRHSs@, and @GRHS@ datatypes}
450 %************************************************************************
452 @Match@es are sets of pattern bindings and right hand sides for
453 functions, patterns or case branches. For example, if a function @g@
459 then \tr{g} has two @Match@es: @(x,y) = y@ and @((x:ys),y) = y+1@.
461 It is always the case that each element of an @[Match]@ list has the
462 same number of @pats@s inside it. This corresponds to saying that
463 a function defined by pattern matching must have the same number of
464 patterns in each equation.
469 [pat] -- The patterns
470 (Maybe (HsType id)) -- A type signature for the result of the match
471 -- Nothing after typechecking
475 -- GRHSs are used both for pattern bindings and for Matches
477 = GRHSs [GRHS id pat] -- Guarded RHSs
478 (HsBinds id pat) -- The where clause
479 PostTcType -- Type of RHS (after type checking)
482 = GRHS [Stmt id pat] -- The RHS is the final ResultStmt
483 -- I considered using a RetunStmt, but
484 -- it printed 'wrong' in error messages
487 mkSimpleMatch :: [pat] -> HsExpr id pat -> Type -> SrcLoc -> Match id pat
488 mkSimpleMatch pats rhs rhs_ty locn
489 = Match pats Nothing (GRHSs (unguardedRHS rhs locn) EmptyBinds rhs_ty)
491 unguardedRHS :: HsExpr id pat -> SrcLoc -> [GRHS id pat]
492 unguardedRHS rhs loc = [GRHS [ResultStmt rhs loc] loc]
495 @getMatchLoc@ takes a @Match@ and returns the
496 source-location gotten from the GRHS inside.
497 THis is something of a nuisance, but no more.
500 getMatchLoc :: Match id pat -> SrcLoc
501 getMatchLoc (Match _ _ (GRHSs (GRHS _ loc : _) _ _)) = loc
504 We know the list must have at least one @Match@ in it.
507 pprMatches :: (Outputable id, Outputable pat)
508 => HsMatchContext id -> [Match id pat] -> SDoc
509 pprMatches ctxt matches = vcat (map (pprMatch ctxt) matches)
511 -- Exported to HsBinds, which can't see the defn of HsMatchContext
512 pprFunBind :: (Outputable id, Outputable pat)
513 => id -> [Match id pat] -> SDoc
514 pprFunBind fun matches = pprMatches (FunRhs fun) matches
516 -- Exported to HsBinds, which can't see the defn of HsMatchContext
517 pprPatBind :: (Outputable id, Outputable pat)
518 => pat -> GRHSs id pat -> SDoc
519 pprPatBind pat grhss = sep [ppr pat, nest 4 (pprGRHSs PatBindRhs grhss)]
522 pprMatch :: (Outputable id, Outputable pat)
523 => HsMatchContext id -> Match id pat -> SDoc
524 pprMatch ctxt (Match pats maybe_ty grhss)
525 = pp_name ctxt <+> sep [sep (map ppr pats),
527 nest 2 (pprGRHSs ctxt grhss)]
529 pp_name (FunRhs fun) = ppr fun
530 pp_name other = empty
531 ppr_maybe_ty = case maybe_ty of
532 Just ty -> dcolon <+> ppr ty
536 pprGRHSs :: (Outputable id, Outputable pat)
537 => HsMatchContext id -> GRHSs id pat -> SDoc
538 pprGRHSs ctxt (GRHSs grhss binds ty)
539 = vcat (map (pprGRHS ctxt) grhss)
541 (if nullBinds binds then empty
542 else text "where" $$ nest 4 (pprDeeper (ppr binds)))
545 pprGRHS :: (Outputable id, Outputable pat)
546 => HsMatchContext id -> GRHS id pat -> SDoc
548 pprGRHS ctxt (GRHS [ResultStmt expr _] locn)
551 pprGRHS ctxt (GRHS guarded locn)
552 = sep [char '|' <+> interpp'SP guards, pp_rhs ctxt expr]
554 ResultStmt expr _ = last guarded -- Last stmt should be a ResultStmt for guards
555 guards = init guarded
557 pp_rhs ctxt rhs = ptext (matchSeparator ctxt) <+> pprDeeper (ppr rhs)
562 %************************************************************************
564 \subsection{Do stmts and list comprehensions}
566 %************************************************************************
570 = BindStmt pat (HsExpr id pat) SrcLoc
571 | LetStmt (HsBinds id pat)
572 | ResultStmt (HsExpr id pat) SrcLoc -- See notes that follow
573 | ExprStmt (HsExpr id pat) PostTcType SrcLoc -- See notes that follow
574 -- The type is the *element type* of the expression
575 | ParStmt [[Stmt id pat]] -- List comp only: parallel set of quals
576 | ParStmtOut [([id], [Stmt id pat])] -- PLC after renaming; the ids are the binders
577 -- bound by the stmts
580 ExprStmts and ResultStmts are a bit tricky, because what they mean
581 depends on the context. Consider the following contexts:
583 A do expression of type (m res_ty)
584 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
585 * ExprStmt E any_ty: do { ....; E; ... }
587 Translation: E >> ...
589 * ResultStmt E: do { ....; E }
593 A list comprehensions of type [elt_ty]
594 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
595 * ExprStmt E Bool: [ .. | .... E ]
597 [ .. | .... | ..., E | ... ]
599 Translation: if E then fail else ...
601 * ResultStmt E: [ E | ... ]
603 Translation: return E
605 A guard list, guarding a RHS of type rhs_ty
606 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
607 * ExprStmt E Bool: f x | ..., E, ... = ...rhs...
609 Translation: if E then fail else ...
611 * ResultStmt E: f x | ...guards... = E
615 Array comprehensions are handled like list comprehensions -=chak
618 consLetStmt :: HsBinds id pat -> [Stmt id pat] -> [Stmt id pat]
619 consLetStmt EmptyBinds stmts = stmts
620 consLetStmt binds stmts = LetStmt binds : stmts
624 instance (Outputable id, Outputable pat) =>
625 Outputable (Stmt id pat) where
626 ppr stmt = pprStmt stmt
628 pprStmt (BindStmt pat expr _) = hsep [ppr pat, ptext SLIT("<-"), ppr expr]
629 pprStmt (LetStmt binds) = hsep [ptext SLIT("let"), pprBinds binds]
630 pprStmt (ExprStmt expr _ _) = ppr expr
631 pprStmt (ResultStmt expr _) = ppr expr
632 pprStmt (ParStmt stmtss)
633 = hsep (map (\stmts -> ptext SLIT("| ") <> ppr stmts) stmtss)
634 pprStmt (ParStmtOut stmtss)
635 = hsep (map (\stmts -> ptext SLIT("| ") <> ppr stmts) stmtss)
637 pprDo :: (Outputable id, Outputable pat)
638 => HsDoContext -> [Stmt id pat] -> SDoc
639 pprDo DoExpr stmts = hang (ptext SLIT("do")) 2 (vcat (map ppr stmts))
640 pprDo ListComp stmts = pprComp brackets stmts
641 pprDo PArrComp stmts = pprComp pabrackets stmts
643 pprComp :: (Outputable id, Outputable pat)
644 => (SDoc -> SDoc) -> [Stmt id pat] -> SDoc
645 pprComp brack stmts = brack $
646 hang (pprExpr expr <+> char '|')
649 ResultStmt expr _ = last stmts -- Last stmt should
650 quals = init stmts -- be an ResultStmt
653 %************************************************************************
655 \subsection{Enumerations and list comprehensions}
657 %************************************************************************
660 data ArithSeqInfo id pat
661 = From (HsExpr id pat)
662 | FromThen (HsExpr id pat)
664 | FromTo (HsExpr id pat)
666 | FromThenTo (HsExpr id pat)
672 instance (Outputable id, Outputable pat) =>
673 Outputable (ArithSeqInfo id pat) where
674 ppr (From e1) = hcat [ppr e1, pp_dotdot]
675 ppr (FromThen e1 e2) = hcat [ppr e1, comma, space, ppr e2, pp_dotdot]
676 ppr (FromTo e1 e3) = hcat [ppr e1, pp_dotdot, ppr e3]
677 ppr (FromThenTo e1 e2 e3)
678 = hcat [ppr e1, comma, space, ppr e2, pp_dotdot, ppr e3]
680 pp_dotdot = ptext SLIT(" .. ")
684 %************************************************************************
686 \subsection{HsMatchCtxt}
688 %************************************************************************
691 data HsMatchContext id -- Context of a Match or Stmt
692 = DoCtxt HsDoContext -- Do-stmt or list comprehension
693 | FunRhs id -- Function binding for f
694 | CaseAlt -- Guard on a case alternative
695 | LambdaExpr -- Lambda
696 | PatBindRhs -- Pattern binding
697 | RecUpd -- Record update
700 data HsDoContext = ListComp
702 | PArrComp -- parallel array comprehension
706 isDoExpr (DoCtxt DoExpr) = True
707 isDoExpr other = False
711 matchSeparator (FunRhs _) = SLIT("=")
712 matchSeparator CaseAlt = SLIT("->")
713 matchSeparator LambdaExpr = SLIT("->")
714 matchSeparator PatBindRhs = SLIT("=")
715 matchSeparator (DoCtxt _) = SLIT("<-")
716 matchSeparator RecUpd = panic "When is this used?"
720 pprMatchContext (FunRhs fun) = ptext SLIT("In the definition of") <+> quotes (ppr fun)
721 pprMatchContext CaseAlt = ptext SLIT("In a case alternative")
722 pprMatchContext RecUpd = ptext SLIT("In a record-update construct")
723 pprMatchContext PatBindRhs = ptext SLIT("In a pattern binding")
724 pprMatchContext LambdaExpr = ptext SLIT("In a lambda abstraction")
725 pprMatchContext (DoCtxt DoExpr) = ptext SLIT("In a 'do' expression pattern binding")
726 pprMatchContext (DoCtxt ListComp) =
727 ptext SLIT("In a 'list comprehension' pattern binding")
728 pprMatchContext (DoCtxt PArrComp) =
729 ptext SLIT("In an 'array comprehension' pattern binding")
731 -- Used to generate the string for a *runtime* error message
732 matchContextErrString (FunRhs fun) = "function " ++ showSDoc (ppr fun)
733 matchContextErrString CaseAlt = "case"
734 matchContextErrString PatBindRhs = "pattern binding"
735 matchContextErrString RecUpd = "record update"
736 matchContextErrString LambdaExpr = "lambda"
737 matchContextErrString (DoCtxt DoExpr) = "'do' expression"
738 matchContextErrString (DoCtxt ListComp) = "list comprehension"
739 matchContextErrString (DoCtxt PArrComp) = "array comprehension"