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 )
20 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
91 [Stmt id pat] -- "do":one or more stmts
95 Type -- Type of the whole expression
98 | ExplicitList -- syntactic list
99 PostTcType -- Gives type of components of list
102 | ExplicitTuple -- tuple
104 -- NB: Unit is ExplicitTuple []
105 -- for tuples, we can get the types
106 -- direct from the components
110 -- Record construction
111 | RecordCon id -- The constructor
112 (HsRecordBinds id pat)
114 | RecordConOut DataCon
115 (HsExpr id pat) -- Data con Id applied to type args
116 (HsRecordBinds id pat)
120 | RecordUpd (HsExpr id pat)
121 (HsRecordBinds id pat)
123 | RecordUpdOut (HsExpr id pat) -- TRANSLATION
124 Type -- Type of *input* record
125 Type -- Type of *result* record (may differ from
126 -- type of input record)
127 [id] -- Dicts needed for construction
128 (HsRecordBinds id pat)
130 | ExprWithTySig -- signature binding
133 | ArithSeqIn -- arithmetic sequence
134 (ArithSeqInfo id pat)
136 (HsExpr id pat) -- (typechecked, of course)
137 (ArithSeqInfo id pat)
139 | HsCCall CLabelString -- call into the C world; string is
140 [HsExpr id pat] -- the C function; exprs are the
141 -- arguments to pass.
142 Safety -- True <=> might cause Haskell
143 -- garbage-collection (must generate
144 -- more paranoid code)
145 Bool -- True <=> it's really a "casm"
146 -- NOTE: this CCall is the *boxed*
147 -- version; the desugarer will convert
148 -- it into the unboxed "ccall#".
149 PostTcType -- The result type; will be *bottom*
150 -- until the typechecker gets ahold of it
152 | HsSCC FAST_STRING -- "set cost centre" (_scc_) annotation
153 (HsExpr id pat) -- expr whose cost is to be measured
157 These constructors only appear temporarily in the parser.
158 The renamer translates them into the Right Thing.
161 | EWildPat -- wildcard
163 | EAsPat id -- as pattern
166 | ELazyPat (HsExpr id pat) -- ~ pattern
168 | HsType (HsType id) -- Explicit type argument; e.g f {| Int |} x y
171 Everything from here on appears only in typechecker output.
174 | TyLam -- TRANSLATION
177 | TyApp -- TRANSLATION
178 (HsExpr id pat) -- generated by Spec
181 -- DictLam and DictApp are "inverses"
189 type HsRecordBinds id pat
190 = [(id, HsExpr id pat, Bool)]
191 -- True <=> source code used "punning",
192 -- i.e. {op1, op2} rather than {op1=e1, op2=e2}
195 A @Dictionary@, unless of length 0 or 1, becomes a tuple. A
196 @ClassDictLam dictvars methods expr@ is, therefore:
198 \ x -> case x of ( dictvars-and-methods-tuple ) -> expr
202 instance (Outputable id, Outputable pat) =>
203 Outputable (HsExpr id pat) where
204 ppr expr = pprExpr expr
208 pprExpr :: (Outputable id, Outputable pat)
209 => HsExpr id pat -> SDoc
211 pprExpr e = pprDeeper (ppr_expr e)
212 pprBinds b = pprDeeper (ppr b)
215 -- Put it in parens if it's an operator
216 | isOperator v = parens (ppr v)
219 ppr_expr (HsIPVar v) = char '?' <> ppr v
220 ppr_expr (HsLit lit) = ppr lit
221 ppr_expr (HsOverLit lit) = ppr lit
223 ppr_expr (HsLam match)
224 = hsep [char '\\', nest 2 (pprMatch LambdaExpr match)]
226 ppr_expr expr@(HsApp e1 e2)
227 = let (fun, args) = collect_args expr [] in
228 (ppr_expr fun) <+> (sep (map ppr_expr args))
230 collect_args (HsApp fun arg) args = collect_args fun (arg:args)
231 collect_args fun args = (fun, args)
233 ppr_expr (OpApp e1 op fixity e2)
235 HsVar v -> pp_infixly v
238 pp_e1 = pprParendExpr e1 -- Add parens to make precedence clear
239 pp_e2 = pprParendExpr e2
242 = hang (pprExpr op) 4 (sep [pp_e1, pp_e2])
245 = sep [pp_e1, hsep [pp_v_op, pp_e2]]
247 pp_v_op | isOperator v = ppr v
248 | otherwise = char '`' <> ppr v <> char '`'
249 -- Put it in backquotes if it's not an operator already
251 ppr_expr (NegApp e) = char '-' <+> pprParendExpr e
253 ppr_expr (HsPar e) = parens (ppr_expr e)
255 ppr_expr (SectionL expr op)
257 HsVar v -> pp_infixly v
260 pp_expr = pprParendExpr expr
262 pp_prefixly = hang (hsep [text " \\ x_ ->", ppr op])
263 4 (hsep [pp_expr, ptext SLIT("x_ )")])
264 pp_infixly v = parens (sep [pp_expr, ppr v])
266 ppr_expr (SectionR op expr)
268 HsVar v -> pp_infixly v
271 pp_expr = pprParendExpr expr
273 pp_prefixly = hang (hsep [text "( \\ x_ ->", ppr op, ptext SLIT("x_")])
274 4 ((<>) pp_expr rparen)
276 = parens (sep [ppr v, pp_expr])
278 ppr_expr (HsCase expr matches _)
279 = sep [ sep [ptext SLIT("case"), nest 4 (pprExpr expr), ptext SLIT("of")],
280 nest 2 (pprMatches CaseAlt matches) ]
282 ppr_expr (HsIf e1 e2 e3 _)
283 = sep [hsep [ptext SLIT("if"), nest 2 (pprExpr e1), ptext SLIT("then")],
288 -- special case: let ... in let ...
289 ppr_expr (HsLet binds expr@(HsLet _ _))
290 = sep [hang (ptext SLIT("let")) 2 (hsep [pprBinds binds, ptext SLIT("in")]),
293 ppr_expr (HsLet binds expr)
294 = sep [hang (ptext SLIT("let")) 2 (pprBinds binds),
295 hang (ptext SLIT("in")) 2 (ppr expr)]
297 ppr_expr (HsWith expr binds)
298 = hsep [ppr expr, ptext SLIT("with"), ppr binds]
300 ppr_expr (HsDo do_or_list_comp stmts _) = pprDo do_or_list_comp stmts
301 ppr_expr (HsDoOut do_or_list_comp stmts _ _ _ _ _) = pprDo do_or_list_comp stmts
303 ppr_expr (ExplicitList _ exprs)
304 = brackets (fsep (punctuate comma (map ppr_expr exprs)))
306 ppr_expr (ExplicitTuple exprs boxity)
307 = tupleParens boxity (sep (punctuate comma (map ppr_expr exprs)))
309 ppr_expr (RecordCon con_id rbinds)
310 = pp_rbinds (ppr con_id) rbinds
311 ppr_expr (RecordConOut data_con con rbinds)
312 = pp_rbinds (ppr con) rbinds
314 ppr_expr (RecordUpd aexp rbinds)
315 = pp_rbinds (pprParendExpr aexp) rbinds
316 ppr_expr (RecordUpdOut aexp _ _ _ rbinds)
317 = pp_rbinds (pprParendExpr aexp) rbinds
319 ppr_expr (ExprWithTySig expr sig)
320 = hang (nest 2 (ppr_expr expr) <+> dcolon)
323 ppr_expr (ArithSeqIn info)
324 = brackets (ppr info)
325 ppr_expr (ArithSeqOut expr info)
326 = brackets (ppr info)
328 ppr_expr EWildPat = char '_'
329 ppr_expr (ELazyPat e) = char '~' <> pprParendExpr e
330 ppr_expr (EAsPat v e) = ppr v <> char '@' <> pprParendExpr e
332 ppr_expr (HsCCall fun args _ is_asm result_ty)
334 then ptext SLIT("_casm_ ``") <> pprCLabelString fun <> ptext SLIT("''")
335 else ptext SLIT("_ccall_") <+> pprCLabelString fun)
336 4 (sep (map pprParendExpr args))
338 ppr_expr (HsSCC lbl expr)
339 = sep [ ptext SLIT("_scc_") <+> doubleQuotes (ptext lbl), pprParendExpr expr ]
341 ppr_expr (TyLam tyvars expr)
342 = hang (hsep [ptext SLIT("/\\"), interppSP tyvars, ptext SLIT("->")])
345 ppr_expr (TyApp expr [ty])
346 = hang (ppr_expr expr) 4 (pprParendType ty)
348 ppr_expr (TyApp expr tys)
349 = hang (ppr_expr expr)
350 4 (brackets (interpp'SP tys))
352 ppr_expr (DictLam dictvars expr)
353 = hang (hsep [ptext SLIT("\\{-dict-}"), interppSP dictvars, ptext SLIT("->")])
356 ppr_expr (DictApp expr [dname])
357 = hang (ppr_expr expr) 4 (ppr dname)
359 ppr_expr (DictApp expr dnames)
360 = hang (ppr_expr expr)
361 4 (brackets (interpp'SP dnames))
363 ppr_expr (HsType id) = ppr id
367 Parenthesize unless very simple:
369 pprParendExpr :: (Outputable id, Outputable pat)
370 => HsExpr id pat -> SDoc
374 pp_as_was = pprExpr expr
381 HsIPVar _ -> pp_as_was
382 ExplicitList _ _ -> pp_as_was
383 ExplicitTuple _ _ -> pp_as_was
386 _ -> parens pp_as_was
389 %************************************************************************
391 \subsection{Record binds}
393 %************************************************************************
396 pp_rbinds :: (Outputable id, Outputable pat)
398 -> HsRecordBinds id pat -> SDoc
400 pp_rbinds thing rbinds
402 4 (braces (sep (punctuate comma (map (pp_rbind) rbinds))))
404 pp_rbind (v, e, pun_flag)
405 = getPprStyle $ \ sty ->
406 if pun_flag && userStyle sty then
409 hsep [ppr v, char '=', ppr e]
414 %************************************************************************
416 \subsection{@Match@, @GRHSs@, and @GRHS@ datatypes}
418 %************************************************************************
420 @Match@es are sets of pattern bindings and right hand sides for
421 functions, patterns or case branches. For example, if a function @g@
427 then \tr{g} has two @Match@es: @(x,y) = y@ and @((x:ys),y) = y+1@.
429 It is always the case that each element of an @[Match]@ list has the
430 same number of @pats@s inside it. This corresponds to saying that
431 a function defined by pattern matching must have the same number of
432 patterns in each equation.
437 [id] -- Tyvars wrt which this match is universally quantified
438 -- empty after typechecking
439 [pat] -- The patterns
440 (Maybe (HsType id)) -- A type signature for the result of the match
441 -- Nothing after typechecking
445 -- GRHSs are used both for pattern bindings and for Matches
447 = GRHSs [GRHS id pat] -- Guarded RHSs
448 (HsBinds id pat) -- The where clause
449 PostTcType -- Type of RHS (after type checking)
452 = GRHS [Stmt id pat] -- The RHS is the final ResultStmt
453 -- I considered using a RetunStmt, but
454 -- it printed 'wrong' in error messages
457 mkSimpleMatch :: [pat] -> HsExpr id pat -> Type -> SrcLoc -> Match id pat
458 mkSimpleMatch pats rhs rhs_ty locn
459 = Match [] pats Nothing (GRHSs (unguardedRHS rhs locn) EmptyBinds rhs_ty)
461 unguardedRHS :: HsExpr id pat -> SrcLoc -> [GRHS id pat]
462 unguardedRHS rhs loc = [GRHS [ResultStmt rhs loc] loc]
465 @getMatchLoc@ takes a @Match@ and returns the
466 source-location gotten from the GRHS inside.
467 THis is something of a nuisance, but no more.
470 getMatchLoc :: Match id pat -> SrcLoc
471 getMatchLoc (Match _ _ _ (GRHSs (GRHS _ loc : _) _ _)) = loc
474 We know the list must have at least one @Match@ in it.
477 pprMatches :: (Outputable id, Outputable pat)
478 => HsMatchContext id -> [Match id pat] -> SDoc
479 pprMatches ctxt matches = vcat (map (pprMatch ctxt) matches)
481 -- Exported to HsBinds, which can't see the defn of HsMatchContext
482 pprFunBind :: (Outputable id, Outputable pat)
483 => id -> [Match id pat] -> SDoc
484 pprFunBind fun matches = pprMatches (FunRhs fun) matches
486 -- Exported to HsBinds, which can't see the defn of HsMatchContext
487 pprPatBind :: (Outputable id, Outputable pat)
488 => pat -> GRHSs id pat -> SDoc
489 pprPatBind pat grhss = sep [ppr pat, nest 4 (pprGRHSs PatBindRhs grhss)]
492 pprMatch :: (Outputable id, Outputable pat)
493 => HsMatchContext id -> Match id pat -> SDoc
494 pprMatch ctxt (Match _ pats maybe_ty grhss)
495 = pp_name ctxt <+> sep [sep (map ppr pats),
497 nest 2 (pprGRHSs ctxt grhss)]
499 pp_name (FunRhs fun) = ppr fun
500 pp_name other = empty
501 ppr_maybe_ty = case maybe_ty of
502 Just ty -> dcolon <+> ppr ty
506 pprGRHSs :: (Outputable id, Outputable pat)
507 => HsMatchContext id -> GRHSs id pat -> SDoc
508 pprGRHSs ctxt (GRHSs grhss binds ty)
509 = vcat (map (pprGRHS ctxt) grhss)
511 (if nullBinds binds then empty
512 else text "where" $$ nest 4 (pprDeeper (ppr binds)))
515 pprGRHS :: (Outputable id, Outputable pat)
516 => HsMatchContext id -> GRHS id pat -> SDoc
518 pprGRHS ctxt (GRHS [ResultStmt expr _] locn)
521 pprGRHS ctxt (GRHS guarded locn)
522 = sep [char '|' <+> interpp'SP guards, pp_rhs ctxt expr]
524 ResultStmt expr _ = last guarded -- Last stmt should be a ResultStmt for guards
525 guards = init guarded
527 pp_rhs ctxt rhs = ptext (matchSeparator ctxt) <+> pprDeeper (ppr rhs)
532 %************************************************************************
534 \subsection{Do stmts and list comprehensions}
536 %************************************************************************
540 = BindStmt pat (HsExpr id pat) SrcLoc
541 | LetStmt (HsBinds id pat)
542 | ResultStmt (HsExpr id pat) SrcLoc -- See notes that follow
543 | ExprStmt (HsExpr id pat) PostTcType SrcLoc -- See notes that follow
544 -- The type is the *element type* of the expression
545 | ParStmt [[Stmt id pat]] -- List comp only: parallel set of quals
546 | ParStmtOut [([id], [Stmt id pat])] -- PLC after renaming; the ids are the binders
547 -- bound by the stmts
550 ExprStmts and ResultStmts are a bit tricky, because what they mean
551 depends on the context. Consider the following contexts:
553 A do expression of type (m res_ty)
554 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
555 * ExprStmt E any_ty: do { ....; E; ... }
557 Translation: E >> ...
559 * ResultStmt E: do { ....; E }
563 A list comprehensions of type [elt_ty]
564 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
565 * ExprStmt E Bool: [ .. | .... E ]
567 [ .. | .... | ..., E | ... ]
569 Translation: if E then fail else ...
571 * ResultStmt E: [ E | ... ]
573 Translation: return E
575 A guard list, guarding a RHS of type rhs_ty
576 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
577 * ExprStmt E Bool: f x | ..., E, ... = ...rhs...
579 Translation: if E then fail else ...
581 * ResultStmt E: f x | ...guards... = E
587 consLetStmt :: HsBinds id pat -> [Stmt id pat] -> [Stmt id pat]
588 consLetStmt EmptyBinds stmts = stmts
589 consLetStmt binds stmts = LetStmt binds : stmts
593 instance (Outputable id, Outputable pat) =>
594 Outputable (Stmt id pat) where
595 ppr stmt = pprStmt stmt
597 pprStmt (BindStmt pat expr _) = hsep [ppr pat, ptext SLIT("<-"), ppr expr]
598 pprStmt (LetStmt binds) = hsep [ptext SLIT("let"), pprBinds binds]
599 pprStmt (ExprStmt expr _ _) = ppr expr
600 pprStmt (ResultStmt expr _) = ppr expr
601 pprStmt (ParStmt stmtss)
602 = hsep (map (\stmts -> ptext SLIT("| ") <> ppr stmts) stmtss)
603 pprStmt (ParStmtOut stmtss)
604 = hsep (map (\stmts -> ptext SLIT("| ") <> ppr stmts) stmtss)
606 pprDo :: (Outputable id, Outputable pat) => HsDoContext -> [Stmt id pat] -> SDoc
607 pprDo DoExpr stmts = hang (ptext SLIT("do")) 2 (vcat (map ppr stmts))
608 pprDo ListComp stmts = brackets $
609 hang (pprExpr expr <+> char '|')
612 ResultStmt expr _ = last stmts -- Last stmt should
613 quals = init stmts -- be an ResultStmt
616 %************************************************************************
618 \subsection{Enumerations and list comprehensions}
620 %************************************************************************
623 data ArithSeqInfo id pat
624 = From (HsExpr id pat)
625 | FromThen (HsExpr id pat)
627 | FromTo (HsExpr id pat)
629 | FromThenTo (HsExpr id pat)
635 instance (Outputable id, Outputable pat) =>
636 Outputable (ArithSeqInfo id pat) where
637 ppr (From e1) = hcat [ppr e1, pp_dotdot]
638 ppr (FromThen e1 e2) = hcat [ppr e1, comma, space, ppr e2, pp_dotdot]
639 ppr (FromTo e1 e3) = hcat [ppr e1, pp_dotdot, ppr e3]
640 ppr (FromThenTo e1 e2 e3)
641 = hcat [ppr e1, comma, space, ppr e2, pp_dotdot, ppr e3]
643 pp_dotdot = ptext SLIT(" .. ")
647 %************************************************************************
649 \subsection{HsMatchCtxt}
651 %************************************************************************
654 data HsMatchContext id -- Context of a Match or Stmt
655 = DoCtxt HsDoContext -- Do-stmt or list comprehension
656 | FunRhs id -- Function binding for f
657 | CaseAlt -- Guard on a case alternative
658 | LambdaExpr -- Lambda
659 | PatBindRhs -- Pattern binding
660 | RecUpd -- Record update
663 data HsDoContext = ListComp | DoExpr
667 isDoExpr (DoCtxt DoExpr) = True
668 isDoExpr other = False
672 matchSeparator (FunRhs _) = SLIT("=")
673 matchSeparator CaseAlt = SLIT("->")
674 matchSeparator LambdaExpr = SLIT("->")
675 matchSeparator PatBindRhs = SLIT("=")
676 matchSeparator (DoCtxt _) = SLIT("<-")
677 matchSeparator RecUpd = panic "When is this used?"
681 pprMatchContext (FunRhs fun) = ptext SLIT("In the definition of") <+> quotes (ppr fun)
682 pprMatchContext CaseAlt = ptext SLIT("In a case alternative")
683 pprMatchContext RecUpd = ptext SLIT("In a record-update construct")
684 pprMatchContext PatBindRhs = ptext SLIT("In a pattern binding")
685 pprMatchContext LambdaExpr = ptext SLIT("In a lambda abstraction")
686 pprMatchContext (DoCtxt DoExpr) = ptext SLIT("In a 'do' expression pattern binding")
687 pprMatchContext (DoCtxt ListComp) = ptext SLIT("In a 'list comprehension' pattern binding")
689 -- Used to generate the string for a *runtime* error message
690 matchContextErrString (FunRhs fun) = "function " ++ showSDoc (ppr fun)
691 matchContextErrString CaseAlt = "case"
692 matchContextErrString PatBindRhs = "pattern binding"
693 matchContextErrString RecUpd = "record update"
694 matchContextErrString LambdaExpr = "lambda"
695 matchContextErrString (DoCtxt DoExpr) = "'do' expression"
696 matchContextErrString (DoCtxt ListComp) = "list comprehension"