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
93 [id] -- Ids for [return,fail,>>=,>>]
95 -- Before type checking, used for rebindable syntax
96 PostTcType -- Type of the whole expression
99 | ExplicitList -- syntactic list
100 PostTcType -- Gives type of components of list
103 | ExplicitPArr -- syntactic parallel array: [:e1, ..., en:]
104 PostTcType -- type of elements of the parallel array
107 | ExplicitTuple -- tuple
109 -- NB: Unit is ExplicitTuple []
110 -- for tuples, we can get the types
111 -- direct from the components
115 -- Record construction
116 | RecordCon id -- The constructor
117 (HsRecordBinds id pat)
119 | RecordConOut DataCon
120 (HsExpr id pat) -- Data con Id applied to type args
121 (HsRecordBinds id pat)
125 | RecordUpd (HsExpr id pat)
126 (HsRecordBinds id pat)
128 | RecordUpdOut (HsExpr id pat) -- TRANSLATION
129 Type -- Type of *input* record
130 Type -- Type of *result* record (may differ from
131 -- type of input record)
132 (HsRecordBinds id pat)
134 | ExprWithTySig -- signature binding
137 | ArithSeqIn -- arithmetic sequence
138 (ArithSeqInfo id pat)
140 (HsExpr id pat) -- (typechecked, of course)
141 (ArithSeqInfo id pat)
142 | PArrSeqIn -- arith. sequence for parallel array
143 (ArithSeqInfo id pat) -- [:e1..e2:] or [:e1, e2..e3:]
145 (HsExpr id pat) -- (typechecked, of course)
146 (ArithSeqInfo id pat)
148 | HsCCall CLabelString -- call into the C world; string is
149 [HsExpr id pat] -- the C function; exprs are the
150 -- arguments to pass.
151 Safety -- True <=> might cause Haskell
152 -- garbage-collection (must generate
153 -- more paranoid code)
154 Bool -- True <=> it's really a "casm"
155 -- NOTE: this CCall is the *boxed*
156 -- version; the desugarer will convert
157 -- it into the unboxed "ccall#".
158 PostTcType -- The result type; will be *bottom*
159 -- until the typechecker gets ahold of it
161 | HsSCC FastString -- "set cost centre" (_scc_) annotation
162 (HsExpr id pat) -- expr whose cost is to be measured
166 These constructors only appear temporarily in the parser.
167 The renamer translates them into the Right Thing.
170 | EWildPat -- wildcard
172 | EAsPat id -- as pattern
175 | ELazyPat (HsExpr id pat) -- ~ pattern
177 | HsType (HsType id) -- Explicit type argument; e.g f {| Int |} x y
180 Everything from here on appears only in typechecker output.
183 | TyLam -- TRANSLATION
186 | TyApp -- TRANSLATION
187 (HsExpr id pat) -- generated by Spec
190 -- DictLam and DictApp are "inverses"
198 type HsRecordBinds id pat
199 = [(id, HsExpr id pat, Bool)]
200 -- True <=> source code used "punning",
201 -- i.e. {op1, op2} rather than {op1=e1, op2=e2}
204 A @Dictionary@, unless of length 0 or 1, becomes a tuple. A
205 @ClassDictLam dictvars methods expr@ is, therefore:
207 \ x -> case x of ( dictvars-and-methods-tuple ) -> expr
211 instance (Outputable id, Outputable pat) =>
212 Outputable (HsExpr id pat) where
213 ppr expr = pprExpr expr
217 pprExpr :: (Outputable id, Outputable pat)
218 => HsExpr id pat -> SDoc
220 pprExpr e = pprDeeper (ppr_expr e)
221 pprBinds b = pprDeeper (ppr b)
224 -- Put it in parens if it's an operator
225 | isOperator v = parens (ppr v)
228 ppr_expr (HsIPVar v) = ppr v
229 ppr_expr (HsLit lit) = ppr lit
230 ppr_expr (HsOverLit lit) = ppr lit
232 ppr_expr (HsLam match)
233 = hsep [char '\\', nest 2 (pprMatch LambdaExpr match)]
235 ppr_expr expr@(HsApp e1 e2)
236 = let (fun, args) = collect_args expr [] in
237 (ppr_expr fun) <+> (sep (map ppr_expr args))
239 collect_args (HsApp fun arg) args = collect_args fun (arg:args)
240 collect_args fun args = (fun, args)
242 ppr_expr (OpApp e1 op fixity e2)
244 HsVar v -> pp_infixly v
247 pp_e1 = pprParendExpr e1 -- Add parens to make precedence clear
248 pp_e2 = pprParendExpr e2
251 = hang (pprExpr op) 4 (sep [pp_e1, pp_e2])
254 = sep [pp_e1, hsep [pp_v_op, pp_e2]]
256 pp_v_op | isOperator v = ppr v
257 | otherwise = char '`' <> ppr v <> char '`'
258 -- Put it in backquotes if it's not an operator already
260 ppr_expr (NegApp e _) = char '-' <+> pprParendExpr e
262 ppr_expr (HsPar e) = parens (ppr_expr e)
264 ppr_expr (SectionL expr op)
266 HsVar v -> pp_infixly v
269 pp_expr = pprParendExpr expr
271 pp_prefixly = hang (hsep [text " \\ x_ ->", ppr op])
272 4 (hsep [pp_expr, ptext SLIT("x_ )")])
273 pp_infixly v = parens (sep [pp_expr, ppr v])
275 ppr_expr (SectionR op expr)
277 HsVar v -> pp_infixly v
280 pp_expr = pprParendExpr expr
282 pp_prefixly = hang (hsep [text "( \\ x_ ->", ppr op, ptext SLIT("x_")])
283 4 ((<>) pp_expr rparen)
285 = parens (sep [ppr v, pp_expr])
287 ppr_expr (HsCase expr matches _)
288 = sep [ sep [ptext SLIT("case"), nest 4 (pprExpr expr), ptext SLIT("of")],
289 nest 2 (pprMatches CaseAlt matches) ]
291 ppr_expr (HsIf e1 e2 e3 _)
292 = sep [hsep [ptext SLIT("if"), nest 2 (pprExpr e1), ptext SLIT("then")],
297 -- special case: let ... in let ...
298 ppr_expr (HsLet binds expr@(HsLet _ _))
299 = sep [hang (ptext SLIT("let")) 2 (hsep [pprBinds binds, ptext SLIT("in")]),
302 ppr_expr (HsLet binds expr)
303 = sep [hang (ptext SLIT("let")) 2 (pprBinds binds),
304 hang (ptext SLIT("in")) 2 (ppr expr)]
306 ppr_expr (HsWith expr binds is_with)
307 = sep [hang (ptext SLIT("let")) 2 (pp_ipbinds binds),
308 hang (ptext SLIT("in")) 2 (ppr expr)]
310 ppr_expr (HsDo do_or_list_comp stmts _ _ _) = pprDo do_or_list_comp stmts
312 ppr_expr (ExplicitList _ exprs)
313 = brackets (fsep (punctuate comma (map ppr_expr exprs)))
315 ppr_expr (ExplicitPArr _ exprs)
316 = pabrackets (fsep (punctuate comma (map ppr_expr exprs)))
318 ppr_expr (ExplicitTuple exprs boxity)
319 = tupleParens boxity (sep (punctuate comma (map ppr_expr exprs)))
321 ppr_expr (RecordCon con_id rbinds)
322 = pp_rbinds (ppr con_id) rbinds
323 ppr_expr (RecordConOut data_con con rbinds)
324 = pp_rbinds (ppr con) rbinds
326 ppr_expr (RecordUpd aexp rbinds)
327 = pp_rbinds (pprParendExpr aexp) rbinds
328 ppr_expr (RecordUpdOut aexp _ _ rbinds)
329 = pp_rbinds (pprParendExpr aexp) rbinds
331 ppr_expr (ExprWithTySig expr sig)
332 = hang (nest 2 (ppr_expr expr) <+> dcolon)
335 ppr_expr (ArithSeqIn info)
336 = brackets (ppr info)
337 ppr_expr (ArithSeqOut expr info)
338 = brackets (ppr info)
340 ppr_expr (PArrSeqIn info)
341 = pabrackets (ppr info)
342 ppr_expr (PArrSeqOut expr info)
343 = pabrackets (ppr info)
345 ppr_expr EWildPat = char '_'
346 ppr_expr (ELazyPat e) = char '~' <> pprParendExpr e
347 ppr_expr (EAsPat v e) = ppr v <> char '@' <> pprParendExpr e
349 ppr_expr (HsCCall fun args _ is_asm result_ty)
351 then ptext SLIT("_casm_ ``") <> pprCLabelString fun <> ptext SLIT("''")
352 else ptext SLIT("_ccall_") <+> pprCLabelString fun)
353 4 (sep (map pprParendExpr args))
355 ppr_expr (HsSCC lbl expr)
356 = sep [ ptext SLIT("_scc_") <+> doubleQuotes (ftext lbl), pprParendExpr expr ]
358 ppr_expr (TyLam tyvars expr)
359 = hang (hsep [ptext SLIT("/\\"), interppSP tyvars, ptext SLIT("->")])
362 ppr_expr (TyApp expr [ty])
363 = hang (ppr_expr expr) 4 (pprParendType ty)
365 ppr_expr (TyApp expr tys)
366 = hang (ppr_expr expr)
367 4 (brackets (interpp'SP tys))
369 ppr_expr (DictLam dictvars expr)
370 = hang (hsep [ptext SLIT("\\{-dict-}"), interppSP dictvars, ptext SLIT("->")])
373 ppr_expr (DictApp expr [dname])
374 = hang (ppr_expr expr) 4 (ppr dname)
376 ppr_expr (DictApp expr dnames)
377 = hang (ppr_expr expr)
378 4 (brackets (interpp'SP dnames))
380 ppr_expr (HsType id) = ppr id
382 -- add parallel array brackets around a document
384 pabrackets :: SDoc -> SDoc
385 pabrackets p = ptext SLIT("[:") <> p <> ptext SLIT(":]")
388 Parenthesize unless very simple:
390 pprParendExpr :: (Outputable id, Outputable pat)
391 => HsExpr id pat -> SDoc
395 pp_as_was = pprExpr expr
402 HsIPVar _ -> pp_as_was
403 ExplicitList _ _ -> pp_as_was
404 ExplicitPArr _ _ -> pp_as_was
405 ExplicitTuple _ _ -> pp_as_was
408 _ -> parens pp_as_was
411 %************************************************************************
413 \subsection{Record binds}
415 %************************************************************************
418 pp_rbinds :: (Outputable id, Outputable pat)
420 -> HsRecordBinds id pat -> SDoc
422 pp_rbinds thing rbinds
424 4 (braces (sep (punctuate comma (map (pp_rbind) rbinds))))
426 pp_rbind (v, e, pun_flag)
427 = getPprStyle $ \ sty ->
428 if pun_flag && userStyle sty then
431 hsep [ppr v, char '=', ppr e]
435 pp_ipbinds :: (Outputable id, Outputable pat)
436 => [(IPName id, HsExpr id pat)] -> SDoc
437 pp_ipbinds pairs = hsep (punctuate semi (map pp_item pairs))
439 pp_item (id,rhs) = ppr id <+> equals <+> ppr_expr rhs
443 %************************************************************************
445 \subsection{@Match@, @GRHSs@, and @GRHS@ datatypes}
447 %************************************************************************
449 @Match@es are sets of pattern bindings and right hand sides for
450 functions, patterns or case branches. For example, if a function @g@
456 then \tr{g} has two @Match@es: @(x,y) = y@ and @((x:ys),y) = y+1@.
458 It is always the case that each element of an @[Match]@ list has the
459 same number of @pats@s inside it. This corresponds to saying that
460 a function defined by pattern matching must have the same number of
461 patterns in each equation.
466 [pat] -- The patterns
467 (Maybe (HsType id)) -- A type signature for the result of the match
468 -- Nothing after typechecking
472 -- GRHSs are used both for pattern bindings and for Matches
474 = GRHSs [GRHS id pat] -- Guarded RHSs
475 (HsBinds id pat) -- The where clause
476 PostTcType -- Type of RHS (after type checking)
479 = GRHS [Stmt id pat] -- The RHS is the final ResultStmt
480 -- I considered using a RetunStmt, but
481 -- it printed 'wrong' in error messages
484 mkSimpleMatch :: [pat] -> HsExpr id pat -> Type -> SrcLoc -> Match id pat
485 mkSimpleMatch pats rhs rhs_ty locn
486 = Match pats Nothing (GRHSs (unguardedRHS rhs locn) EmptyBinds rhs_ty)
488 unguardedRHS :: HsExpr id pat -> SrcLoc -> [GRHS id pat]
489 unguardedRHS rhs loc = [GRHS [ResultStmt rhs loc] loc]
492 @getMatchLoc@ takes a @Match@ and returns the
493 source-location gotten from the GRHS inside.
494 THis is something of a nuisance, but no more.
497 getMatchLoc :: Match id pat -> SrcLoc
498 getMatchLoc (Match _ _ (GRHSs (GRHS _ loc : _) _ _)) = loc
501 We know the list must have at least one @Match@ in it.
504 pprMatches :: (Outputable id, Outputable pat)
505 => HsMatchContext id -> [Match id pat] -> SDoc
506 pprMatches ctxt matches = vcat (map (pprMatch ctxt) matches)
508 -- Exported to HsBinds, which can't see the defn of HsMatchContext
509 pprFunBind :: (Outputable id, Outputable pat)
510 => id -> [Match id pat] -> SDoc
511 pprFunBind fun matches = pprMatches (FunRhs fun) matches
513 -- Exported to HsBinds, which can't see the defn of HsMatchContext
514 pprPatBind :: (Outputable id, Outputable pat)
515 => pat -> GRHSs id pat -> SDoc
516 pprPatBind pat grhss = sep [ppr pat, nest 4 (pprGRHSs PatBindRhs grhss)]
519 pprMatch :: (Outputable id, Outputable pat)
520 => HsMatchContext id -> Match id pat -> SDoc
521 pprMatch ctxt (Match pats maybe_ty grhss)
522 = pp_name ctxt <+> sep [sep (map ppr pats),
524 nest 2 (pprGRHSs ctxt grhss)]
526 pp_name (FunRhs fun) = ppr fun
527 pp_name other = empty
528 ppr_maybe_ty = case maybe_ty of
529 Just ty -> dcolon <+> ppr ty
533 pprGRHSs :: (Outputable id, Outputable pat)
534 => HsMatchContext id -> GRHSs id pat -> SDoc
535 pprGRHSs ctxt (GRHSs grhss binds ty)
536 = vcat (map (pprGRHS ctxt) grhss)
538 (if nullBinds binds then empty
539 else text "where" $$ nest 4 (pprDeeper (ppr binds)))
542 pprGRHS :: (Outputable id, Outputable pat)
543 => HsMatchContext id -> GRHS id pat -> SDoc
545 pprGRHS ctxt (GRHS [ResultStmt expr _] locn)
548 pprGRHS ctxt (GRHS guarded locn)
549 = sep [char '|' <+> interpp'SP guards, pp_rhs ctxt expr]
551 ResultStmt expr _ = last guarded -- Last stmt should be a ResultStmt for guards
552 guards = init guarded
554 pp_rhs ctxt rhs = matchSeparator ctxt <+> pprDeeper (ppr rhs)
559 %************************************************************************
561 \subsection{Do stmts and list comprehensions}
563 %************************************************************************
567 = BindStmt pat (HsExpr id pat) SrcLoc
568 | LetStmt (HsBinds id pat)
569 | ResultStmt (HsExpr id pat) SrcLoc -- See notes that follow
570 | ExprStmt (HsExpr id pat) PostTcType SrcLoc -- See notes that follow
571 -- The type is the *element type* of the expression
572 | ParStmt [[Stmt id pat]] -- List comp only: parallel set of quals
573 | ParStmtOut [([id], [Stmt id pat])] -- PLC after renaming; the ids are the binders
574 -- bound by the stmts
577 ExprStmts and ResultStmts are a bit tricky, because what they mean
578 depends on the context. Consider the following contexts:
580 A do expression of type (m res_ty)
581 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
582 * ExprStmt E any_ty: do { ....; E; ... }
584 Translation: E >> ...
586 * ResultStmt E: do { ....; E }
590 A list comprehensions of type [elt_ty]
591 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
592 * ExprStmt E Bool: [ .. | .... E ]
594 [ .. | .... | ..., E | ... ]
596 Translation: if E then fail else ...
598 * ResultStmt E: [ E | ... ]
600 Translation: return E
602 A guard list, guarding a RHS of type rhs_ty
603 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
604 * ExprStmt E Bool: f x | ..., E, ... = ...rhs...
606 Translation: if E then fail else ...
608 * ResultStmt E: f x | ...guards... = E
612 Array comprehensions are handled like list comprehensions -=chak
615 consLetStmt :: HsBinds id pat -> [Stmt id pat] -> [Stmt id pat]
616 consLetStmt EmptyBinds stmts = stmts
617 consLetStmt binds stmts = LetStmt binds : stmts
621 instance (Outputable id, Outputable pat) =>
622 Outputable (Stmt id pat) where
623 ppr stmt = pprStmt stmt
625 pprStmt (BindStmt pat expr _) = hsep [ppr pat, ptext SLIT("<-"), ppr expr]
626 pprStmt (LetStmt binds) = hsep [ptext SLIT("let"), pprBinds binds]
627 pprStmt (ExprStmt expr _ _) = ppr expr
628 pprStmt (ResultStmt expr _) = ppr expr
629 pprStmt (ParStmt stmtss)
630 = hsep (map (\stmts -> ptext SLIT("| ") <> ppr stmts) stmtss)
631 pprStmt (ParStmtOut stmtss)
632 = hsep (map (\stmts -> ptext SLIT("| ") <> ppr stmts) stmtss)
634 pprDo :: (Outputable id, Outputable pat)
635 => HsDoContext -> [Stmt id pat] -> SDoc
636 pprDo DoExpr stmts = hang (ptext SLIT("do")) 2 (vcat (map ppr stmts))
637 pprDo ListComp stmts = pprComp brackets stmts
638 pprDo PArrComp stmts = pprComp pabrackets stmts
640 pprComp :: (Outputable id, Outputable pat)
641 => (SDoc -> SDoc) -> [Stmt id pat] -> SDoc
642 pprComp brack stmts = brack $
643 hang (pprExpr expr <+> char '|')
646 ResultStmt expr _ = last stmts -- Last stmt should
647 quals = init stmts -- be an ResultStmt
650 %************************************************************************
652 \subsection{Enumerations and list comprehensions}
654 %************************************************************************
657 data ArithSeqInfo id pat
658 = From (HsExpr id pat)
659 | FromThen (HsExpr id pat)
661 | FromTo (HsExpr id pat)
663 | FromThenTo (HsExpr id pat)
669 instance (Outputable id, Outputable pat) =>
670 Outputable (ArithSeqInfo id pat) where
671 ppr (From e1) = hcat [ppr e1, pp_dotdot]
672 ppr (FromThen e1 e2) = hcat [ppr e1, comma, space, ppr e2, pp_dotdot]
673 ppr (FromTo e1 e3) = hcat [ppr e1, pp_dotdot, ppr e3]
674 ppr (FromThenTo e1 e2 e3)
675 = hcat [ppr e1, comma, space, ppr e2, pp_dotdot, ppr e3]
677 pp_dotdot = ptext SLIT(" .. ")
681 %************************************************************************
683 \subsection{HsMatchCtxt}
685 %************************************************************************
688 data HsMatchContext id -- Context of a Match or Stmt
689 = DoCtxt HsDoContext -- Do-stmt or list comprehension
690 | FunRhs id -- Function binding for f
691 | CaseAlt -- Guard on a case alternative
692 | LambdaExpr -- Lambda
693 | PatBindRhs -- Pattern binding
694 | RecUpd -- Record update
697 data HsDoContext = ListComp
699 | PArrComp -- parallel array comprehension
703 isDoExpr (DoCtxt DoExpr) = True
704 isDoExpr other = False
708 matchSeparator (FunRhs _) = ptext SLIT("=")
709 matchSeparator CaseAlt = ptext SLIT("->")
710 matchSeparator LambdaExpr = ptext SLIT("->")
711 matchSeparator PatBindRhs = ptext SLIT("=")
712 matchSeparator (DoCtxt _) = ptext SLIT("<-")
713 matchSeparator RecUpd = panic "When is this used?"
717 pprMatchContext (FunRhs fun) = ptext SLIT("In the definition of") <+> quotes (ppr fun)
718 pprMatchContext CaseAlt = ptext SLIT("In a case alternative")
719 pprMatchContext RecUpd = ptext SLIT("In a record-update construct")
720 pprMatchContext PatBindRhs = ptext SLIT("In a pattern binding")
721 pprMatchContext LambdaExpr = ptext SLIT("In a lambda abstraction")
722 pprMatchContext (DoCtxt DoExpr) = ptext SLIT("In a 'do' expression pattern binding")
723 pprMatchContext (DoCtxt ListComp) =
724 ptext SLIT("In a 'list comprehension' pattern binding")
725 pprMatchContext (DoCtxt PArrComp) =
726 ptext SLIT("In an 'array comprehension' pattern binding")
728 -- Used to generate the string for a *runtime* error message
729 matchContextErrString (FunRhs fun) = "function " ++ showSDoc (ppr fun)
730 matchContextErrString CaseAlt = "case"
731 matchContextErrString PatBindRhs = "pattern binding"
732 matchContextErrString RecUpd = "record update"
733 matchContextErrString LambdaExpr = "lambda"
734 matchContextErrString (DoCtxt DoExpr) = "'do' expression"
735 matchContextErrString (DoCtxt ListComp) = "list comprehension"
736 matchContextErrString (DoCtxt PArrComp) = "array comprehension"