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 )
33 %************************************************************************
35 \subsection{Expressions proper}
37 %************************************************************************
41 = HsVar id -- variable
42 | HsIPVar (IPName id) -- implicit parameter
43 | HsOverLit HsOverLit -- Overloaded literals; eliminated by type checker
44 | HsLit HsLit -- Simple (non-overloaded) literals
46 | HsLam (Match id pat) -- lambda
47 | HsApp (HsExpr id pat) -- application
50 -- Operator applications:
51 -- NB Bracketed ops such as (+) come out as Vars.
53 -- NB We need an expr for the operator in an OpApp/Section since
54 -- the typechecker may need to apply the operator to a few types.
56 | OpApp (HsExpr id pat) -- left operand
57 (HsExpr id pat) -- operator
58 Fixity -- Renamer adds fixity; bottom until then
59 (HsExpr id pat) -- right operand
61 -- We preserve prefix negation and parenthesis for the precedence parser.
62 -- They are eventually removed by the type checker.
64 | NegApp (HsExpr id pat) -- negated expr
65 Name -- Name of 'negate' (see RnEnv.lookupSyntaxName)
67 | HsPar (HsExpr id pat) -- parenthesised expr
69 | SectionL (HsExpr id pat) -- operand
70 (HsExpr id pat) -- operator
71 | SectionR (HsExpr id pat) -- operator
72 (HsExpr id pat) -- operand
74 | HsCase (HsExpr id pat)
78 | HsIf (HsExpr id pat) -- predicate
79 (HsExpr id pat) -- then part
80 (HsExpr id pat) -- else part
83 | HsLet (HsBinds id pat) -- let(rec)
86 | HsWith (HsExpr id pat) -- implicit parameter binding
87 [(IPName id, HsExpr id pat)]
88 Bool -- True <=> this was a 'with' binding
89 -- (tmp, until 'with' is removed)
92 [Stmt id pat] -- "do":one or more stmts
96 [Stmt id pat] -- "do":one or more stmts
97 [id] -- ids for [return,fail,>>=,>>]
99 Type -- Type of the whole expression
102 | ExplicitList -- syntactic list
103 PostTcType -- Gives type of components of list
106 | ExplicitPArr -- syntactic parallel array: [:e1, ..., en:]
107 PostTcType -- type of elements of the parallel array
110 | ExplicitTuple -- tuple
112 -- NB: Unit is ExplicitTuple []
113 -- for tuples, we can get the types
114 -- direct from the components
118 -- Record construction
119 | RecordCon id -- The constructor
120 (HsRecordBinds id pat)
122 | RecordConOut DataCon
123 (HsExpr id pat) -- Data con Id applied to type args
124 (HsRecordBinds id pat)
128 | RecordUpd (HsExpr id pat)
129 (HsRecordBinds id pat)
131 | RecordUpdOut (HsExpr id pat) -- TRANSLATION
132 Type -- Type of *input* record
133 Type -- Type of *result* record (may differ from
134 -- type of input record)
135 (HsRecordBinds id pat)
137 | ExprWithTySig -- signature binding
140 | ArithSeqIn -- arithmetic sequence
141 (ArithSeqInfo id pat)
143 (HsExpr id pat) -- (typechecked, of course)
144 (ArithSeqInfo id pat)
145 | PArrSeqIn -- arith. sequence for parallel array
146 (ArithSeqInfo id pat) -- [:e1..e2:] or [:e1, e2..e3:]
148 (HsExpr id pat) -- (typechecked, of course)
149 (ArithSeqInfo id pat)
151 | HsCCall CLabelString -- call into the C world; string is
152 [HsExpr id pat] -- the C function; exprs are the
153 -- arguments to pass.
154 Safety -- True <=> might cause Haskell
155 -- garbage-collection (must generate
156 -- more paranoid code)
157 Bool -- True <=> it's really a "casm"
158 -- NOTE: this CCall is the *boxed*
159 -- version; the desugarer will convert
160 -- it into the unboxed "ccall#".
161 PostTcType -- The result type; will be *bottom*
162 -- until the typechecker gets ahold of it
164 | HsSCC FastString -- "set cost centre" (_scc_) annotation
165 (HsExpr id pat) -- expr whose cost is to be measured
169 These constructors only appear temporarily in the parser.
170 The renamer translates them into the Right Thing.
173 | EWildPat -- wildcard
175 | EAsPat id -- as pattern
178 | ELazyPat (HsExpr id pat) -- ~ pattern
180 | HsType (HsType id) -- Explicit type argument; e.g f {| Int |} x y
183 Everything from here on appears only in typechecker output.
186 | TyLam -- TRANSLATION
189 | TyApp -- TRANSLATION
190 (HsExpr id pat) -- generated by Spec
193 -- DictLam and DictApp are "inverses"
201 type HsRecordBinds id pat
202 = [(id, HsExpr id pat, Bool)]
203 -- True <=> source code used "punning",
204 -- i.e. {op1, op2} rather than {op1=e1, op2=e2}
207 A @Dictionary@, unless of length 0 or 1, becomes a tuple. A
208 @ClassDictLam dictvars methods expr@ is, therefore:
210 \ x -> case x of ( dictvars-and-methods-tuple ) -> expr
214 instance (Outputable id, Outputable pat) =>
215 Outputable (HsExpr id pat) where
216 ppr expr = pprExpr expr
220 pprExpr :: (Outputable id, Outputable pat)
221 => HsExpr id pat -> SDoc
223 pprExpr e = pprDeeper (ppr_expr e)
224 pprBinds b = pprDeeper (ppr b)
227 -- Put it in parens if it's an operator
228 | isOperator v = parens (ppr v)
231 ppr_expr (HsIPVar v) = ppr v
232 ppr_expr (HsLit lit) = ppr lit
233 ppr_expr (HsOverLit lit) = ppr lit
235 ppr_expr (HsLam match)
236 = hsep [char '\\', nest 2 (pprMatch LambdaExpr match)]
238 ppr_expr expr@(HsApp e1 e2)
239 = let (fun, args) = collect_args expr [] in
240 (ppr_expr fun) <+> (sep (map ppr_expr args))
242 collect_args (HsApp fun arg) args = collect_args fun (arg:args)
243 collect_args fun args = (fun, args)
245 ppr_expr (OpApp e1 op fixity e2)
247 HsVar v -> pp_infixly v
250 pp_e1 = pprParendExpr e1 -- Add parens to make precedence clear
251 pp_e2 = pprParendExpr e2
254 = hang (pprExpr op) 4 (sep [pp_e1, pp_e2])
257 = sep [pp_e1, hsep [pp_v_op, pp_e2]]
259 pp_v_op | isOperator v = ppr v
260 | otherwise = char '`' <> ppr v <> char '`'
261 -- Put it in backquotes if it's not an operator already
263 ppr_expr (NegApp e _) = char '-' <+> pprParendExpr e
265 ppr_expr (HsPar e) = parens (ppr_expr e)
267 ppr_expr (SectionL expr op)
269 HsVar v -> pp_infixly v
272 pp_expr = pprParendExpr expr
274 pp_prefixly = hang (hsep [text " \\ x_ ->", ppr op])
275 4 (hsep [pp_expr, ptext SLIT("x_ )")])
276 pp_infixly v = parens (sep [pp_expr, ppr v])
278 ppr_expr (SectionR op expr)
280 HsVar v -> pp_infixly v
283 pp_expr = pprParendExpr expr
285 pp_prefixly = hang (hsep [text "( \\ x_ ->", ppr op, ptext SLIT("x_")])
286 4 ((<>) pp_expr rparen)
288 = parens (sep [ppr v, pp_expr])
290 ppr_expr (HsCase expr matches _)
291 = sep [ sep [ptext SLIT("case"), nest 4 (pprExpr expr), ptext SLIT("of")],
292 nest 2 (pprMatches CaseAlt matches) ]
294 ppr_expr (HsIf e1 e2 e3 _)
295 = sep [hsep [ptext SLIT("if"), nest 2 (pprExpr e1), ptext SLIT("then")],
300 -- special case: let ... in let ...
301 ppr_expr (HsLet binds expr@(HsLet _ _))
302 = sep [hang (ptext SLIT("let")) 2 (hsep [pprBinds binds, ptext SLIT("in")]),
305 ppr_expr (HsLet binds expr)
306 = sep [hang (ptext SLIT("let")) 2 (pprBinds binds),
307 hang (ptext SLIT("in")) 2 (ppr expr)]
309 ppr_expr (HsWith expr binds is_with)
310 = sep [hang (ptext SLIT("let")) 2 (pp_ipbinds binds),
311 hang (ptext SLIT("in")) 2 (ppr expr)]
313 ppr_expr (HsDo do_or_list_comp stmts _) = pprDo do_or_list_comp stmts
314 ppr_expr (HsDoOut do_or_list_comp stmts _ _ _) = pprDo do_or_list_comp stmts
316 ppr_expr (ExplicitList _ exprs)
317 = brackets (fsep (punctuate comma (map ppr_expr exprs)))
319 ppr_expr (ExplicitPArr _ exprs)
320 = pabrackets (fsep (punctuate comma (map ppr_expr exprs)))
322 ppr_expr (ExplicitTuple exprs boxity)
323 = tupleParens boxity (sep (punctuate comma (map ppr_expr exprs)))
325 ppr_expr (RecordCon con_id rbinds)
326 = pp_rbinds (ppr con_id) rbinds
327 ppr_expr (RecordConOut data_con con rbinds)
328 = pp_rbinds (ppr con) rbinds
330 ppr_expr (RecordUpd aexp rbinds)
331 = pp_rbinds (pprParendExpr aexp) rbinds
332 ppr_expr (RecordUpdOut aexp _ _ rbinds)
333 = pp_rbinds (pprParendExpr aexp) rbinds
335 ppr_expr (ExprWithTySig expr sig)
336 = hang (nest 2 (ppr_expr expr) <+> dcolon)
339 ppr_expr (ArithSeqIn info)
340 = brackets (ppr info)
341 ppr_expr (ArithSeqOut expr info)
342 = brackets (ppr info)
344 ppr_expr (PArrSeqIn info)
345 = pabrackets (ppr info)
346 ppr_expr (PArrSeqOut expr info)
347 = pabrackets (ppr info)
349 ppr_expr EWildPat = char '_'
350 ppr_expr (ELazyPat e) = char '~' <> pprParendExpr e
351 ppr_expr (EAsPat v e) = ppr v <> char '@' <> pprParendExpr e
353 ppr_expr (HsCCall fun args _ is_asm result_ty)
355 then ptext SLIT("_casm_ ``") <> pprCLabelString fun <> ptext SLIT("''")
356 else ptext SLIT("_ccall_") <+> pprCLabelString fun)
357 4 (sep (map pprParendExpr args))
359 ppr_expr (HsSCC lbl expr)
360 = sep [ ptext SLIT("_scc_") <+> doubleQuotes (ftext lbl), pprParendExpr expr ]
362 ppr_expr (TyLam tyvars expr)
363 = hang (hsep [ptext SLIT("/\\"), interppSP tyvars, ptext SLIT("->")])
366 ppr_expr (TyApp expr [ty])
367 = hang (ppr_expr expr) 4 (pprParendType ty)
369 ppr_expr (TyApp expr tys)
370 = hang (ppr_expr expr)
371 4 (brackets (interpp'SP tys))
373 ppr_expr (DictLam dictvars expr)
374 = hang (hsep [ptext SLIT("\\{-dict-}"), interppSP dictvars, ptext SLIT("->")])
377 ppr_expr (DictApp expr [dname])
378 = hang (ppr_expr expr) 4 (ppr dname)
380 ppr_expr (DictApp expr dnames)
381 = hang (ppr_expr expr)
382 4 (brackets (interpp'SP dnames))
384 ppr_expr (HsType id) = ppr id
386 -- add parallel array brackets around a document
388 pabrackets :: SDoc -> SDoc
389 pabrackets p = ptext SLIT("[:") <> p <> ptext SLIT(":]")
392 Parenthesize unless very simple:
394 pprParendExpr :: (Outputable id, Outputable pat)
395 => HsExpr id pat -> SDoc
399 pp_as_was = pprExpr expr
406 HsIPVar _ -> pp_as_was
407 ExplicitList _ _ -> pp_as_was
408 ExplicitPArr _ _ -> pp_as_was
409 ExplicitTuple _ _ -> pp_as_was
412 _ -> parens pp_as_was
415 %************************************************************************
417 \subsection{Record binds}
419 %************************************************************************
422 pp_rbinds :: (Outputable id, Outputable pat)
424 -> HsRecordBinds id pat -> SDoc
426 pp_rbinds thing rbinds
428 4 (braces (sep (punctuate comma (map (pp_rbind) rbinds))))
430 pp_rbind (v, e, pun_flag)
431 = getPprStyle $ \ sty ->
432 if pun_flag && userStyle sty then
435 hsep [ppr v, char '=', ppr e]
439 pp_ipbinds :: (Outputable id, Outputable pat)
440 => [(IPName id, HsExpr id pat)] -> SDoc
441 pp_ipbinds pairs = hsep (punctuate semi (map pp_item pairs))
443 pp_item (id,rhs) = ppr id <+> equals <+> ppr_expr rhs
447 %************************************************************************
449 \subsection{@Match@, @GRHSs@, and @GRHS@ datatypes}
451 %************************************************************************
453 @Match@es are sets of pattern bindings and right hand sides for
454 functions, patterns or case branches. For example, if a function @g@
460 then \tr{g} has two @Match@es: @(x,y) = y@ and @((x:ys),y) = y+1@.
462 It is always the case that each element of an @[Match]@ list has the
463 same number of @pats@s inside it. This corresponds to saying that
464 a function defined by pattern matching must have the same number of
465 patterns in each equation.
470 [pat] -- The patterns
471 (Maybe (HsType id)) -- A type signature for the result of the match
472 -- Nothing after typechecking
476 -- GRHSs are used both for pattern bindings and for Matches
478 = GRHSs [GRHS id pat] -- Guarded RHSs
479 (HsBinds id pat) -- The where clause
480 PostTcType -- Type of RHS (after type checking)
483 = GRHS [Stmt id pat] -- The RHS is the final ResultStmt
484 -- I considered using a RetunStmt, but
485 -- it printed 'wrong' in error messages
488 mkSimpleMatch :: [pat] -> HsExpr id pat -> Type -> SrcLoc -> Match id pat
489 mkSimpleMatch pats rhs rhs_ty locn
490 = Match pats Nothing (GRHSs (unguardedRHS rhs locn) EmptyBinds rhs_ty)
492 unguardedRHS :: HsExpr id pat -> SrcLoc -> [GRHS id pat]
493 unguardedRHS rhs loc = [GRHS [ResultStmt rhs loc] loc]
496 @getMatchLoc@ takes a @Match@ and returns the
497 source-location gotten from the GRHS inside.
498 THis is something of a nuisance, but no more.
501 getMatchLoc :: Match id pat -> SrcLoc
502 getMatchLoc (Match _ _ (GRHSs (GRHS _ loc : _) _ _)) = loc
505 We know the list must have at least one @Match@ in it.
508 pprMatches :: (Outputable id, Outputable pat)
509 => HsMatchContext id -> [Match id pat] -> SDoc
510 pprMatches ctxt matches = vcat (map (pprMatch ctxt) matches)
512 -- Exported to HsBinds, which can't see the defn of HsMatchContext
513 pprFunBind :: (Outputable id, Outputable pat)
514 => id -> [Match id pat] -> SDoc
515 pprFunBind fun matches = pprMatches (FunRhs fun) matches
517 -- Exported to HsBinds, which can't see the defn of HsMatchContext
518 pprPatBind :: (Outputable id, Outputable pat)
519 => pat -> GRHSs id pat -> SDoc
520 pprPatBind pat grhss = sep [ppr pat, nest 4 (pprGRHSs PatBindRhs grhss)]
523 pprMatch :: (Outputable id, Outputable pat)
524 => HsMatchContext id -> Match id pat -> SDoc
525 pprMatch ctxt (Match pats maybe_ty grhss)
526 = pp_name ctxt <+> sep [sep (map ppr pats),
528 nest 2 (pprGRHSs ctxt grhss)]
530 pp_name (FunRhs fun) = ppr fun
531 pp_name other = empty
532 ppr_maybe_ty = case maybe_ty of
533 Just ty -> dcolon <+> ppr ty
537 pprGRHSs :: (Outputable id, Outputable pat)
538 => HsMatchContext id -> GRHSs id pat -> SDoc
539 pprGRHSs ctxt (GRHSs grhss binds ty)
540 = vcat (map (pprGRHS ctxt) grhss)
542 (if nullBinds binds then empty
543 else text "where" $$ nest 4 (pprDeeper (ppr binds)))
546 pprGRHS :: (Outputable id, Outputable pat)
547 => HsMatchContext id -> GRHS id pat -> SDoc
549 pprGRHS ctxt (GRHS [ResultStmt expr _] locn)
552 pprGRHS ctxt (GRHS guarded locn)
553 = sep [char '|' <+> interpp'SP guards, pp_rhs ctxt expr]
555 ResultStmt expr _ = last guarded -- Last stmt should be a ResultStmt for guards
556 guards = init guarded
558 pp_rhs ctxt rhs = matchSeparator ctxt <+> pprDeeper (ppr rhs)
563 %************************************************************************
565 \subsection{Do stmts and list comprehensions}
567 %************************************************************************
571 = BindStmt pat (HsExpr id pat) SrcLoc
572 | LetStmt (HsBinds id pat)
573 | ResultStmt (HsExpr id pat) SrcLoc -- See notes that follow
574 | ExprStmt (HsExpr id pat) PostTcType SrcLoc -- See notes that follow
575 -- The type is the *element type* of the expression
576 | ParStmt [[Stmt id pat]] -- List comp only: parallel set of quals
577 | ParStmtOut [([id], [Stmt id pat])] -- PLC after renaming; the ids are the binders
578 -- bound by the stmts
581 ExprStmts and ResultStmts are a bit tricky, because what they mean
582 depends on the context. Consider the following contexts:
584 A do expression of type (m res_ty)
585 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
586 * ExprStmt E any_ty: do { ....; E; ... }
588 Translation: E >> ...
590 * ResultStmt E: do { ....; E }
594 A list comprehensions of type [elt_ty]
595 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
596 * ExprStmt E Bool: [ .. | .... E ]
598 [ .. | .... | ..., E | ... ]
600 Translation: if E then fail else ...
602 * ResultStmt E: [ E | ... ]
604 Translation: return E
606 A guard list, guarding a RHS of type rhs_ty
607 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
608 * ExprStmt E Bool: f x | ..., E, ... = ...rhs...
610 Translation: if E then fail else ...
612 * ResultStmt E: f x | ...guards... = E
616 Array comprehensions are handled like list comprehensions -=chak
619 consLetStmt :: HsBinds id pat -> [Stmt id pat] -> [Stmt id pat]
620 consLetStmt EmptyBinds stmts = stmts
621 consLetStmt binds stmts = LetStmt binds : stmts
625 instance (Outputable id, Outputable pat) =>
626 Outputable (Stmt id pat) where
627 ppr stmt = pprStmt stmt
629 pprStmt (BindStmt pat expr _) = hsep [ppr pat, ptext SLIT("<-"), ppr expr]
630 pprStmt (LetStmt binds) = hsep [ptext SLIT("let"), pprBinds binds]
631 pprStmt (ExprStmt expr _ _) = ppr expr
632 pprStmt (ResultStmt expr _) = ppr expr
633 pprStmt (ParStmt stmtss)
634 = hsep (map (\stmts -> ptext SLIT("| ") <> ppr stmts) stmtss)
635 pprStmt (ParStmtOut stmtss)
636 = hsep (map (\stmts -> ptext SLIT("| ") <> ppr stmts) stmtss)
638 pprDo :: (Outputable id, Outputable pat)
639 => HsDoContext -> [Stmt id pat] -> SDoc
640 pprDo DoExpr stmts = hang (ptext SLIT("do")) 2 (vcat (map ppr stmts))
641 pprDo ListComp stmts = pprComp brackets stmts
642 pprDo PArrComp stmts = pprComp pabrackets stmts
644 pprComp :: (Outputable id, Outputable pat)
645 => (SDoc -> SDoc) -> [Stmt id pat] -> SDoc
646 pprComp brack stmts = brack $
647 hang (pprExpr expr <+> char '|')
650 ResultStmt expr _ = last stmts -- Last stmt should
651 quals = init stmts -- be an ResultStmt
654 %************************************************************************
656 \subsection{Enumerations and list comprehensions}
658 %************************************************************************
661 data ArithSeqInfo id pat
662 = From (HsExpr id pat)
663 | FromThen (HsExpr id pat)
665 | FromTo (HsExpr id pat)
667 | FromThenTo (HsExpr id pat)
673 instance (Outputable id, Outputable pat) =>
674 Outputable (ArithSeqInfo id pat) where
675 ppr (From e1) = hcat [ppr e1, pp_dotdot]
676 ppr (FromThen e1 e2) = hcat [ppr e1, comma, space, ppr e2, pp_dotdot]
677 ppr (FromTo e1 e3) = hcat [ppr e1, pp_dotdot, ppr e3]
678 ppr (FromThenTo e1 e2 e3)
679 = hcat [ppr e1, comma, space, ppr e2, pp_dotdot, ppr e3]
681 pp_dotdot = ptext SLIT(" .. ")
685 %************************************************************************
687 \subsection{HsMatchCtxt}
689 %************************************************************************
692 data HsMatchContext id -- Context of a Match or Stmt
693 = DoCtxt HsDoContext -- Do-stmt or list comprehension
694 | FunRhs id -- Function binding for f
695 | CaseAlt -- Guard on a case alternative
696 | LambdaExpr -- Lambda
697 | PatBindRhs -- Pattern binding
698 | RecUpd -- Record update
701 data HsDoContext = ListComp
703 | PArrComp -- parallel array comprehension
707 isDoExpr (DoCtxt DoExpr) = True
708 isDoExpr other = False
712 matchSeparator (FunRhs _) = ptext SLIT("=")
713 matchSeparator CaseAlt = ptext SLIT("->")
714 matchSeparator LambdaExpr = ptext SLIT("->")
715 matchSeparator PatBindRhs = ptext SLIT("=")
716 matchSeparator (DoCtxt _) = ptext SLIT("<-")
717 matchSeparator RecUpd = panic "When is this used?"
721 pprMatchContext (FunRhs fun) = ptext SLIT("In the definition of") <+> quotes (ppr fun)
722 pprMatchContext CaseAlt = ptext SLIT("In a case alternative")
723 pprMatchContext RecUpd = ptext SLIT("In a record-update construct")
724 pprMatchContext PatBindRhs = ptext SLIT("In a pattern binding")
725 pprMatchContext LambdaExpr = ptext SLIT("In a lambda abstraction")
726 pprMatchContext (DoCtxt DoExpr) = ptext SLIT("In a 'do' expression pattern binding")
727 pprMatchContext (DoCtxt ListComp) =
728 ptext SLIT("In a 'list comprehension' pattern binding")
729 pprMatchContext (DoCtxt PArrComp) =
730 ptext SLIT("In an 'array comprehension' pattern binding")
732 -- Used to generate the string for a *runtime* error message
733 matchContextErrString (FunRhs fun) = "function " ++ showSDoc (ppr fun)
734 matchContextErrString CaseAlt = "case"
735 matchContextErrString PatBindRhs = "pattern binding"
736 matchContextErrString RecUpd = "record update"
737 matchContextErrString LambdaExpr = "lambda"
738 matchContextErrString (DoCtxt DoExpr) = "'do' expression"
739 matchContextErrString (DoCtxt ListComp) = "list comprehension"
740 matchContextErrString (DoCtxt PArrComp) = "array comprehension"