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 HsLit ( HsLit, HsOverLit )
14 import BasicTypes ( Fixity(..) )
15 import HsTypes ( HsType )
16 import HsImpExp ( isOperator )
19 import ForeignCall ( Safety )
22 import PprType ( pprParendType )
25 import DataCon ( DataCon )
26 import CStrings ( CLabelString, pprCLabelString )
27 import BasicTypes ( Boxity, tupleParens )
28 import SrcLoc ( SrcLoc )
31 %************************************************************************
33 \subsection{Expressions proper}
35 %************************************************************************
39 = HsVar id -- variable
40 | HsIPVar id -- implicit parameter
41 | HsOverLit HsOverLit -- Overloaded literals; eliminated by type checker
42 | HsLit HsLit -- Simple (non-overloaded) literals
44 | HsLam (Match id pat) -- lambda
45 | HsApp (HsExpr id pat) -- application
48 -- Operator applications:
49 -- NB Bracketed ops such as (+) come out as Vars.
51 -- NB We need an expr for the operator in an OpApp/Section since
52 -- the typechecker may need to apply the operator to a few types.
54 | OpApp (HsExpr id pat) -- left operand
55 (HsExpr id pat) -- operator
56 Fixity -- Renamer adds fixity; bottom until then
57 (HsExpr id pat) -- right operand
59 -- We preserve prefix negation and parenthesis for the precedence parser.
60 -- They are eventually removed by the type checker.
62 | NegApp (HsExpr id pat) -- negated expr
64 | HsPar (HsExpr id pat) -- parenthesised expr
66 | SectionL (HsExpr id pat) -- operand
67 (HsExpr id pat) -- operator
68 | SectionR (HsExpr id pat) -- operator
69 (HsExpr id pat) -- operand
71 | HsCase (HsExpr id pat)
75 | HsIf (HsExpr id pat) -- predicate
76 (HsExpr id pat) -- then part
77 (HsExpr id pat) -- else part
80 | HsLet (HsBinds id pat) -- let(rec)
83 | HsWith (HsExpr id pat) -- implicit parameter binding
87 [Stmt id pat] -- "do":one or more stmts
90 | HsDoOut HsMatchContext
91 [Stmt id pat] -- "do":one or more stmts
95 Type -- Type of the whole expression
98 | ExplicitList -- syntactic list
100 | ExplicitListOut -- TRANSLATION
101 Type -- Gives type of components of list
104 | ExplicitTuple -- tuple
106 -- NB: Unit is ExplicitTuple []
107 -- for tuples, we can get the types
108 -- direct from the components
112 -- Record construction
113 | RecordCon id -- The constructor
114 (HsRecordBinds id pat)
116 | RecordConOut DataCon
117 (HsExpr id pat) -- Data con Id applied to type args
118 (HsRecordBinds id pat)
122 | RecordUpd (HsExpr id pat)
123 (HsRecordBinds id pat)
125 | RecordUpdOut (HsExpr id pat) -- TRANSLATION
126 Type -- Type of *result* record (may differ from
127 -- type of input record)
128 [id] -- Dicts needed for construction
129 (HsRecordBinds id pat)
131 | ExprWithTySig -- signature binding
134 | ArithSeqIn -- arithmetic sequence
135 (ArithSeqInfo id pat)
137 (HsExpr id pat) -- (typechecked, of course)
138 (ArithSeqInfo id pat)
140 | HsCCall CLabelString -- call into the C world; string is
141 [HsExpr id pat] -- the C function; exprs are the
142 -- arguments to pass.
143 Safety -- True <=> might cause Haskell
144 -- garbage-collection (must generate
145 -- more paranoid code)
146 Bool -- True <=> it's really a "casm"
147 -- NOTE: this CCall is the *boxed*
148 -- version; the desugarer will convert
149 -- it into the unboxed "ccall#".
150 Type -- The result type; will be *bottom*
151 -- until the typechecker gets ahold of it
153 | HsSCC FAST_STRING -- "set cost centre" (_scc_) annotation
154 (HsExpr id pat) -- expr whose cost is to be measured
158 These constructors only appear temporarily in the parser.
159 The renamer translates them into the Right Thing.
162 | EWildPat -- wildcard
164 | EAsPat id -- as pattern
167 | ELazyPat (HsExpr id pat) -- ~ pattern
169 | HsType (HsType id) -- Explicit type argument; e.g f {| Int |} x y
172 Everything from here on appears only in typechecker output.
175 | TyLam -- TRANSLATION
178 | TyApp -- TRANSLATION
179 (HsExpr id pat) -- generated by Spec
182 -- DictLam and DictApp are "inverses"
190 type HsRecordBinds id pat
191 = [(id, HsExpr id pat, Bool)]
192 -- True <=> source code used "punning",
193 -- i.e. {op1, op2} rather than {op1=e1, op2=e2}
196 A @Dictionary@, unless of length 0 or 1, becomes a tuple. A
197 @ClassDictLam dictvars methods expr@ is, therefore:
199 \ x -> case x of ( dictvars-and-methods-tuple ) -> expr
203 instance (Outputable id, Outputable pat) =>
204 Outputable (HsExpr id pat) where
205 ppr expr = pprExpr expr
209 pprExpr :: (Outputable id, Outputable pat)
210 => HsExpr id pat -> SDoc
212 pprExpr e = pprDeeper (ppr_expr e)
213 pprBinds b = pprDeeper (ppr b)
216 -- Put it in parens if it's an operator
217 | isOperator v = parens (ppr v)
220 ppr_expr (HsIPVar v) = char '?' <> ppr v
221 ppr_expr (HsLit lit) = ppr lit
222 ppr_expr (HsOverLit lit) = ppr lit
224 ppr_expr (HsLam match)
225 = hsep [char '\\', nest 2 (pprMatch (True,empty) match)]
227 ppr_expr expr@(HsApp e1 e2)
228 = let (fun, args) = collect_args expr [] in
229 (ppr_expr fun) <+> (sep (map ppr_expr args))
231 collect_args (HsApp fun arg) args = collect_args fun (arg:args)
232 collect_args fun args = (fun, args)
234 ppr_expr (OpApp e1 op fixity e2)
236 HsVar v -> pp_infixly v
239 pp_e1 = pprParendExpr e1 -- Add parens to make precedence clear
240 pp_e2 = pprParendExpr e2
243 = hang (pprExpr op) 4 (sep [pp_e1, pp_e2])
246 = sep [pp_e1, hsep [pp_v_op, pp_e2]]
248 pp_v_op | isOperator v = ppr v
249 | otherwise = char '`' <> ppr v <> char '`'
250 -- Put it in backquotes if it's not an operator already
252 ppr_expr (NegApp e) = char '-' <+> pprParendExpr e
254 ppr_expr (HsPar e) = parens (ppr_expr e)
256 ppr_expr (SectionL expr op)
258 HsVar v -> pp_infixly v
261 pp_expr = pprParendExpr expr
263 pp_prefixly = hang (hsep [text " \\ x_ ->", ppr op])
264 4 (hsep [pp_expr, ptext SLIT("x_ )")])
265 pp_infixly v = parens (sep [pp_expr, ppr v])
267 ppr_expr (SectionR op expr)
269 HsVar v -> pp_infixly v
272 pp_expr = pprParendExpr expr
274 pp_prefixly = hang (hsep [text "( \\ x_ ->", ppr op, ptext SLIT("x_")])
275 4 ((<>) pp_expr rparen)
277 = parens (sep [ppr v, pp_expr])
279 ppr_expr (HsCase expr matches _)
280 = sep [ sep [ptext SLIT("case"), nest 4 (pprExpr expr), ptext SLIT("of")],
281 nest 2 (pprMatches (True, empty) matches) ]
283 ppr_expr (HsIf e1 e2 e3 _)
284 = sep [hsep [ptext SLIT("if"), nest 2 (pprExpr e1), ptext SLIT("then")],
289 -- special case: let ... in let ...
290 ppr_expr (HsLet binds expr@(HsLet _ _))
291 = sep [hang (ptext SLIT("let")) 2 (hsep [pprBinds binds, ptext SLIT("in")]),
294 ppr_expr (HsLet binds expr)
295 = sep [hang (ptext SLIT("let")) 2 (pprBinds binds),
296 hang (ptext SLIT("in")) 2 (ppr expr)]
298 ppr_expr (HsWith expr binds)
299 = hsep [ppr expr, ptext SLIT("with"), ppr binds]
301 ppr_expr (HsDo do_or_list_comp stmts _) = pprDo do_or_list_comp stmts
302 ppr_expr (HsDoOut do_or_list_comp stmts _ _ _ _ _) = pprDo do_or_list_comp stmts
304 ppr_expr (ExplicitList exprs)
305 = brackets (fsep (punctuate comma (map ppr_expr exprs)))
306 ppr_expr (ExplicitListOut ty exprs)
307 = brackets (fsep (punctuate comma (map ppr_expr exprs)))
309 ppr_expr (ExplicitTuple exprs boxity)
310 = tupleParens boxity (sep (punctuate comma (map ppr_expr exprs)))
312 ppr_expr (RecordCon con_id rbinds)
313 = pp_rbinds (ppr con_id) rbinds
314 ppr_expr (RecordConOut data_con con rbinds)
315 = pp_rbinds (ppr con) rbinds
317 ppr_expr (RecordUpd aexp rbinds)
318 = pp_rbinds (pprParendExpr aexp) rbinds
319 ppr_expr (RecordUpdOut aexp _ _ rbinds)
320 = pp_rbinds (pprParendExpr aexp) rbinds
322 ppr_expr (ExprWithTySig expr sig)
323 = hang (nest 2 (ppr_expr expr) <+> dcolon)
326 ppr_expr (ArithSeqIn info)
327 = brackets (ppr info)
328 ppr_expr (ArithSeqOut expr info)
329 = brackets (ppr info)
331 ppr_expr EWildPat = char '_'
332 ppr_expr (ELazyPat e) = char '~' <> pprParendExpr e
333 ppr_expr (EAsPat v e) = ppr v <> char '@' <> pprParendExpr e
335 ppr_expr (HsCCall fun args _ is_asm result_ty)
337 then ptext SLIT("_casm_ ``") <> pprCLabelString fun <> ptext SLIT("''")
338 else ptext SLIT("_ccall_") <+> pprCLabelString fun)
339 4 (sep (map pprParendExpr args))
341 ppr_expr (HsSCC lbl expr)
342 = sep [ ptext SLIT("_scc_") <+> doubleQuotes (ptext lbl), pprParendExpr expr ]
344 ppr_expr (TyLam tyvars expr)
345 = hang (hsep [ptext SLIT("/\\"), interppSP tyvars, ptext SLIT("->")])
348 ppr_expr (TyApp expr [ty])
349 = hang (ppr_expr expr) 4 (pprParendType ty)
351 ppr_expr (TyApp expr tys)
352 = hang (ppr_expr expr)
353 4 (brackets (interpp'SP tys))
355 ppr_expr (DictLam dictvars expr)
356 = hang (hsep [ptext SLIT("\\{-dict-}"), interppSP dictvars, ptext SLIT("->")])
359 ppr_expr (DictApp expr [dname])
360 = hang (ppr_expr expr) 4 (ppr dname)
362 ppr_expr (DictApp expr dnames)
363 = hang (ppr_expr expr)
364 4 (brackets (interpp'SP dnames))
366 ppr_expr (HsType id) = ppr id
370 Parenthesize unless very simple:
372 pprParendExpr :: (Outputable id, Outputable pat)
373 => HsExpr id pat -> SDoc
377 pp_as_was = pprExpr expr
384 HsIPVar _ -> pp_as_was
385 ExplicitList _ -> pp_as_was
386 ExplicitListOut _ _ -> pp_as_was
387 ExplicitTuple _ _ -> pp_as_was
390 _ -> parens pp_as_was
393 %************************************************************************
395 \subsection{Record binds}
397 %************************************************************************
400 pp_rbinds :: (Outputable id, Outputable pat)
402 -> HsRecordBinds id pat -> SDoc
404 pp_rbinds thing rbinds
406 4 (braces (sep (punctuate comma (map (pp_rbind) rbinds))))
408 pp_rbind (v, e, pun_flag)
409 = getPprStyle $ \ sty ->
410 if pun_flag && userStyle sty then
413 hsep [ppr v, char '=', ppr e]
418 %************************************************************************
420 \subsection{@Match@, @GRHSs@, and @GRHS@ datatypes}
422 %************************************************************************
424 @Match@es are sets of pattern bindings and right hand sides for
425 functions, patterns or case branches. For example, if a function @g@
431 then \tr{g} has two @Match@es: @(x,y) = y@ and @((x:ys),y) = y+1@.
433 It is always the case that each element of an @[Match]@ list has the
434 same number of @pats@s inside it. This corresponds to saying that
435 a function defined by pattern matching must have the same number of
436 patterns in each equation.
441 [id] -- Tyvars wrt which this match is universally quantified
442 -- empty after typechecking
443 [pat] -- The patterns
444 (Maybe (HsType id)) -- A type signature for the result of the match
445 -- Nothing after typechecking
449 -- GRHSs are used both for pattern bindings and for Matches
451 = GRHSs [GRHS id pat] -- Guarded RHSs
452 (HsBinds id pat) -- The where clause
453 (Maybe Type) -- Just rhs_ty after type checking
456 = GRHS [Stmt id pat] -- The RHS is the final ResultStmt
457 -- I considered using a RetunStmt, but
458 -- it printed 'wrong' in error messages
461 mkSimpleMatch :: [pat] -> HsExpr id pat -> Maybe Type -> SrcLoc -> Match id pat
462 mkSimpleMatch pats rhs maybe_rhs_ty locn
463 = Match [] pats Nothing (GRHSs (unguardedRHS rhs locn) EmptyBinds maybe_rhs_ty)
465 unguardedRHS :: HsExpr id pat -> SrcLoc -> [GRHS id pat]
466 unguardedRHS rhs loc = [GRHS [ResultStmt rhs loc] loc]
469 @getMatchLoc@ takes a @Match@ and returns the
470 source-location gotten from the GRHS inside.
471 THis is something of a nuisance, but no more.
474 getMatchLoc :: Match id pat -> SrcLoc
475 getMatchLoc (Match _ _ _ (GRHSs (GRHS _ loc : _) _ _)) = loc
478 We know the list must have at least one @Match@ in it.
481 pprMatches :: (Outputable id, Outputable pat)
482 => (Bool, SDoc) -> [Match id pat] -> SDoc
483 pprMatches print_info matches = vcat (map (pprMatch print_info) matches)
486 pprMatch :: (Outputable id, Outputable pat)
487 => (Bool, SDoc) -> Match id pat -> SDoc
488 pprMatch print_info@(is_case, name) (Match _ pats maybe_ty grhss)
489 = maybe_name <+> sep [sep (map ppr pats),
491 nest 2 (pprGRHSs is_case grhss)]
493 maybe_name | is_case = empty
495 ppr_maybe_ty = case maybe_ty of
496 Just ty -> dcolon <+> ppr ty
500 pprGRHSs :: (Outputable id, Outputable pat)
501 => Bool -> GRHSs id pat -> SDoc
502 pprGRHSs is_case (GRHSs grhss binds maybe_ty)
503 = vcat (map (pprGRHS is_case) grhss)
505 (if nullBinds binds then empty
506 else text "where" $$ nest 4 (pprDeeper (ppr binds)))
509 pprGRHS :: (Outputable id, Outputable pat)
510 => Bool -> GRHS id pat -> SDoc
512 pprGRHS is_case (GRHS [ResultStmt expr _] locn)
513 = pp_rhs is_case expr
515 pprGRHS is_case (GRHS guarded locn)
516 = sep [char '|' <+> interpp'SP guards, pp_rhs is_case expr]
518 ResultStmt expr _ = last guarded -- Last stmt should be a ResultStmt for guards
519 guards = init guarded
521 pp_rhs is_case rhs = text (if is_case then "->" else "=") <+> pprDeeper (ppr rhs)
526 %************************************************************************
528 \subsection{Do stmts and list comprehensions}
530 %************************************************************************
534 = BindStmt pat (HsExpr id pat) SrcLoc
535 | LetStmt (HsBinds id pat)
536 | ResultStmt (HsExpr id pat) SrcLoc -- See notes that follow
537 | ExprStmt (HsExpr id pat) SrcLoc -- See notes that follow
538 | ParStmt [[Stmt id pat]] -- List comp only: parallel set of quals
539 | ParStmtOut [([id], [Stmt id pat])] -- PLC after renaming; the ids are the binders
540 -- bound by the stmts
543 ExprStmts and ResultStmts are a bit tricky, because what they mean
544 depends on the context. Consider the following contexts:
546 A do expression of type (m res_ty)
547 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
548 * ExprStmt E: do { ....; E; ... }
550 Translation: E >> ...
552 * ResultStmt E: do { ....; E }
556 A list comprehensions of type [elt_ty]
557 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
558 * ExprStmt E: [ .. | .... E ]
560 [ .. | .... | ..., E | ... ]
562 Translation: if E then fail else ...
564 * ResultStmt E: [ E | ... ]
566 Translation: return E
568 A guard list, guarding a RHS of type rhs_ty
569 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
570 * ExprStmt E: f x | ..., E, ... = ...rhs...
572 Translation: if E then fail else ...
574 * ResultStmt E: f x | ...guards... = E
580 consLetStmt :: HsBinds id pat -> [Stmt id pat] -> [Stmt id pat]
581 consLetStmt EmptyBinds stmts = stmts
582 consLetStmt binds stmts = LetStmt binds : stmts
586 instance (Outputable id, Outputable pat) =>
587 Outputable (Stmt id pat) where
588 ppr stmt = pprStmt stmt
590 pprStmt (BindStmt pat expr _) = hsep [ppr pat, ptext SLIT("<-"), ppr expr]
591 pprStmt (LetStmt binds) = hsep [ptext SLIT("let"), pprBinds binds]
592 pprStmt (ExprStmt expr _) = ppr expr
593 pprStmt (ResultStmt expr _) = ppr expr
594 pprStmt (ParStmt stmtss)
595 = hsep (map (\stmts -> ptext SLIT("| ") <> ppr stmts) stmtss)
596 pprStmt (ParStmtOut stmtss)
597 = hsep (map (\stmts -> ptext SLIT("| ") <> ppr stmts) stmtss)
599 pprDo :: (Outputable id, Outputable pat) => HsMatchContext -> [Stmt id pat] -> SDoc
600 pprDo DoExpr stmts = hang (ptext SLIT("do")) 2 (vcat (map ppr stmts))
601 pprDo ListComp stmts = brackets $
602 hang (pprExpr expr <+> char '|')
605 ResultStmt expr _ = last stmts -- Last stmt should
606 quals = init stmts -- be an ResultStmt
609 %************************************************************************
611 \subsection{Enumerations and list comprehensions}
613 %************************************************************************
616 data ArithSeqInfo id pat
617 = From (HsExpr id pat)
618 | FromThen (HsExpr id pat)
620 | FromTo (HsExpr id pat)
622 | FromThenTo (HsExpr id pat)
628 instance (Outputable id, Outputable pat) =>
629 Outputable (ArithSeqInfo id pat) where
630 ppr (From e1) = hcat [ppr e1, pp_dotdot]
631 ppr (FromThen e1 e2) = hcat [ppr e1, comma, space, ppr e2, pp_dotdot]
632 ppr (FromTo e1 e3) = hcat [ppr e1, pp_dotdot, ppr e3]
633 ppr (FromThenTo e1 e2 e3)
634 = hcat [ppr e1, comma, space, ppr e2, pp_dotdot, ppr e3]
636 pp_dotdot = ptext SLIT(" .. ")
640 %************************************************************************
642 \subsection{HsMatchCtxt}
644 %************************************************************************
647 data HsMatchContext -- Context of a Match or Stmt
648 = ListComp -- List comprehension
649 | DoExpr -- Do Statment
651 | FunRhs Name -- Function binding for f
652 | CaseAlt -- Guard on a case alternative
653 | LambdaExpr -- Lambda
654 | PatBindRhs -- Pattern binding
655 | RecUpd -- Record update
658 -- It's convenient to have FunRhs as a Name
659 -- throughout so that HsMatchContext doesn't
660 -- need to be parameterised.
661 -- In the RdrName world we never use the FunRhs variant.
665 isDoExpr DoExpr = True
666 isDoExpr other = False
668 isDoOrListComp ListComp = True
669 isDoOrListComp DoExpr = True
670 isDoOrListComp other = False
674 matchSeparator (FunRhs _) = SLIT("=")
675 matchSeparator CaseAlt = SLIT("->")
676 matchSeparator LambdaExpr = SLIT("->")
677 matchSeparator PatBindRhs = SLIT("=")
678 matchSeparator DoExpr = SLIT("<-")
679 matchSeparator ListComp = SLIT("<-")
680 matchSeparator RecUpd = panic "When is this used?"
684 pprMatchContext (FunRhs fun) = ptext SLIT("In the definition of") <+> quotes (ppr fun)
685 pprMatchContext CaseAlt = ptext SLIT("In a group of case alternatives beginning")
686 pprMatchContext RecUpd = ptext SLIT("In a record-update construct")
687 pprMatchContext PatBindRhs = ptext SLIT("In a pattern binding")
688 pprMatchContext LambdaExpr = ptext SLIT("In a lambda abstraction")
689 pprMatchContext DoExpr = ptext SLIT("In a 'do' expression pattern binding")
690 pprMatchContext ListComp = ptext SLIT("In a 'list comprehension' pattern binding")