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)]
89 [Stmt id pat] -- "do":one or more stmts
93 [Stmt id pat] -- "do":one or more stmts
97 Type -- Type of the whole expression
100 | ExplicitList -- syntactic list
101 PostTcType -- Gives type of components of list
104 | ExplicitPArr -- syntactic parallel array: [:e1, ..., en:]
105 PostTcType -- type of elements of the parallel array
108 | ExplicitTuple -- tuple
110 -- NB: Unit is ExplicitTuple []
111 -- for tuples, we can get the types
112 -- direct from the components
116 -- Record construction
117 | RecordCon id -- The constructor
118 (HsRecordBinds id pat)
120 | RecordConOut DataCon
121 (HsExpr id pat) -- Data con Id applied to type args
122 (HsRecordBinds id pat)
126 | RecordUpd (HsExpr id pat)
127 (HsRecordBinds id pat)
129 | RecordUpdOut (HsExpr id pat) -- TRANSLATION
130 Type -- Type of *input* record
131 Type -- Type of *result* record (may differ from
132 -- type of input record)
133 (HsRecordBinds id pat)
135 | ExprWithTySig -- signature binding
138 | ArithSeqIn -- arithmetic sequence
139 (ArithSeqInfo id pat)
141 (HsExpr id pat) -- (typechecked, of course)
142 (ArithSeqInfo id pat)
143 | PArrSeqIn -- arith. sequence for parallel array
144 (ArithSeqInfo id pat) -- [:e1..e2:] or [:e1, e2..e3:]
146 (HsExpr id pat) -- (typechecked, of course)
147 (ArithSeqInfo id pat)
149 | HsCCall CLabelString -- call into the C world; string is
150 [HsExpr id pat] -- the C function; exprs are the
151 -- arguments to pass.
152 Safety -- True <=> might cause Haskell
153 -- garbage-collection (must generate
154 -- more paranoid code)
155 Bool -- True <=> it's really a "casm"
156 -- NOTE: this CCall is the *boxed*
157 -- version; the desugarer will convert
158 -- it into the unboxed "ccall#".
159 PostTcType -- The result type; will be *bottom*
160 -- until the typechecker gets ahold of it
162 | HsSCC FAST_STRING -- "set cost centre" (_scc_) annotation
163 (HsExpr id pat) -- expr whose cost is to be measured
167 These constructors only appear temporarily in the parser.
168 The renamer translates them into the Right Thing.
171 | EWildPat -- wildcard
173 | EAsPat id -- as pattern
176 | ELazyPat (HsExpr id pat) -- ~ pattern
178 | HsType (HsType id) -- Explicit type argument; e.g f {| Int |} x y
181 Everything from here on appears only in typechecker output.
184 | TyLam -- TRANSLATION
187 | TyApp -- TRANSLATION
188 (HsExpr id pat) -- generated by Spec
191 -- DictLam and DictApp are "inverses"
199 type HsRecordBinds id pat
200 = [(id, HsExpr id pat, Bool)]
201 -- True <=> source code used "punning",
202 -- i.e. {op1, op2} rather than {op1=e1, op2=e2}
205 A @Dictionary@, unless of length 0 or 1, becomes a tuple. A
206 @ClassDictLam dictvars methods expr@ is, therefore:
208 \ x -> case x of ( dictvars-and-methods-tuple ) -> expr
212 instance (Outputable id, Outputable pat) =>
213 Outputable (HsExpr id pat) where
214 ppr expr = pprExpr expr
218 pprExpr :: (Outputable id, Outputable pat)
219 => HsExpr id pat -> SDoc
221 pprExpr e = pprDeeper (ppr_expr e)
222 pprBinds b = pprDeeper (ppr b)
225 -- Put it in parens if it's an operator
226 | isOperator v = parens (ppr v)
229 ppr_expr (HsIPVar v) = ppr v
230 ppr_expr (HsLit lit) = ppr lit
231 ppr_expr (HsOverLit lit) = ppr lit
233 ppr_expr (HsLam match)
234 = hsep [char '\\', nest 2 (pprMatch LambdaExpr match)]
236 ppr_expr expr@(HsApp e1 e2)
237 = let (fun, args) = collect_args expr [] in
238 (ppr_expr fun) <+> (sep (map ppr_expr args))
240 collect_args (HsApp fun arg) args = collect_args fun (arg:args)
241 collect_args fun args = (fun, args)
243 ppr_expr (OpApp e1 op fixity e2)
245 HsVar v -> pp_infixly v
248 pp_e1 = pprParendExpr e1 -- Add parens to make precedence clear
249 pp_e2 = pprParendExpr e2
252 = hang (pprExpr op) 4 (sep [pp_e1, pp_e2])
255 = sep [pp_e1, hsep [pp_v_op, pp_e2]]
257 pp_v_op | isOperator v = ppr v
258 | otherwise = char '`' <> ppr v <> char '`'
259 -- Put it in backquotes if it's not an operator already
261 ppr_expr (NegApp e _) = char '-' <+> pprParendExpr e
263 ppr_expr (HsPar e) = parens (ppr_expr e)
265 ppr_expr (SectionL expr op)
267 HsVar v -> pp_infixly v
270 pp_expr = pprParendExpr expr
272 pp_prefixly = hang (hsep [text " \\ x_ ->", ppr op])
273 4 (hsep [pp_expr, ptext SLIT("x_ )")])
274 pp_infixly v = parens (sep [pp_expr, ppr v])
276 ppr_expr (SectionR op expr)
278 HsVar v -> pp_infixly v
281 pp_expr = pprParendExpr expr
283 pp_prefixly = hang (hsep [text "( \\ x_ ->", ppr op, ptext SLIT("x_")])
284 4 ((<>) pp_expr rparen)
286 = parens (sep [ppr v, pp_expr])
288 ppr_expr (HsCase expr matches _)
289 = sep [ sep [ptext SLIT("case"), nest 4 (pprExpr expr), ptext SLIT("of")],
290 nest 2 (pprMatches CaseAlt matches) ]
292 ppr_expr (HsIf e1 e2 e3 _)
293 = sep [hsep [ptext SLIT("if"), nest 2 (pprExpr e1), ptext SLIT("then")],
298 -- special case: let ... in let ...
299 ppr_expr (HsLet binds expr@(HsLet _ _))
300 = sep [hang (ptext SLIT("let")) 2 (hsep [pprBinds binds, ptext SLIT("in")]),
303 ppr_expr (HsLet binds expr)
304 = sep [hang (ptext SLIT("let")) 2 (pprBinds binds),
305 hang (ptext SLIT("in")) 2 (ppr expr)]
307 ppr_expr (HsWith expr binds)
308 = hsep [ppr expr, ptext SLIT("with"), pp_ipbinds binds]
310 ppr_expr (HsDo do_or_list_comp stmts _) = pprDo do_or_list_comp stmts
311 ppr_expr (HsDoOut do_or_list_comp stmts _ _ _ _ _) = pprDo do_or_list_comp stmts
313 ppr_expr (ExplicitList _ exprs)
314 = brackets (fsep (punctuate comma (map ppr_expr exprs)))
316 ppr_expr (ExplicitPArr _ exprs)
317 = pabrackets (fsep (punctuate comma (map ppr_expr exprs)))
319 ppr_expr (ExplicitTuple exprs boxity)
320 = tupleParens boxity (sep (punctuate comma (map ppr_expr exprs)))
322 ppr_expr (RecordCon con_id rbinds)
323 = pp_rbinds (ppr con_id) rbinds
324 ppr_expr (RecordConOut data_con con rbinds)
325 = pp_rbinds (ppr con) rbinds
327 ppr_expr (RecordUpd aexp rbinds)
328 = pp_rbinds (pprParendExpr aexp) rbinds
329 ppr_expr (RecordUpdOut aexp _ _ rbinds)
330 = pp_rbinds (pprParendExpr aexp) rbinds
332 ppr_expr (ExprWithTySig expr sig)
333 = hang (nest 2 (ppr_expr expr) <+> dcolon)
336 ppr_expr (ArithSeqIn info)
337 = brackets (ppr info)
338 ppr_expr (ArithSeqOut expr info)
339 = brackets (ppr info)
341 ppr_expr (PArrSeqIn info)
342 = pabrackets (ppr info)
343 ppr_expr (PArrSeqOut expr info)
344 = pabrackets (ppr info)
346 ppr_expr EWildPat = char '_'
347 ppr_expr (ELazyPat e) = char '~' <> pprParendExpr e
348 ppr_expr (EAsPat v e) = ppr v <> char '@' <> pprParendExpr e
350 ppr_expr (HsCCall fun args _ is_asm result_ty)
352 then ptext SLIT("_casm_ ``") <> pprCLabelString fun <> ptext SLIT("''")
353 else ptext SLIT("_ccall_") <+> pprCLabelString fun)
354 4 (sep (map pprParendExpr args))
356 ppr_expr (HsSCC lbl expr)
357 = sep [ ptext SLIT("_scc_") <+> doubleQuotes (ptext lbl), pprParendExpr expr ]
359 ppr_expr (TyLam tyvars expr)
360 = hang (hsep [ptext SLIT("/\\"), interppSP tyvars, ptext SLIT("->")])
363 ppr_expr (TyApp expr [ty])
364 = hang (ppr_expr expr) 4 (pprParendType ty)
366 ppr_expr (TyApp expr tys)
367 = hang (ppr_expr expr)
368 4 (brackets (interpp'SP tys))
370 ppr_expr (DictLam dictvars expr)
371 = hang (hsep [ptext SLIT("\\{-dict-}"), interppSP dictvars, ptext SLIT("->")])
374 ppr_expr (DictApp expr [dname])
375 = hang (ppr_expr expr) 4 (ppr dname)
377 ppr_expr (DictApp expr dnames)
378 = hang (ppr_expr expr)
379 4 (brackets (interpp'SP dnames))
381 ppr_expr (HsType id) = ppr id
383 -- add parallel array brackets around a document
385 pabrackets :: SDoc -> SDoc
386 pabrackets p = ptext SLIT("[:") <> p <> ptext SLIT(":]")
389 Parenthesize unless very simple:
391 pprParendExpr :: (Outputable id, Outputable pat)
392 => HsExpr id pat -> SDoc
396 pp_as_was = pprExpr expr
403 HsIPVar _ -> pp_as_was
404 ExplicitList _ _ -> pp_as_was
405 ExplicitPArr _ _ -> pp_as_was
406 ExplicitTuple _ _ -> pp_as_was
409 _ -> parens pp_as_was
412 %************************************************************************
414 \subsection{Record binds}
416 %************************************************************************
419 pp_rbinds :: (Outputable id, Outputable pat)
421 -> HsRecordBinds id pat -> SDoc
423 pp_rbinds thing rbinds
425 4 (braces (sep (punctuate comma (map (pp_rbind) rbinds))))
427 pp_rbind (v, e, pun_flag)
428 = getPprStyle $ \ sty ->
429 if pun_flag && userStyle sty then
432 hsep [ppr v, char '=', ppr e]
436 pp_ipbinds :: (Outputable id, Outputable pat)
437 => [(IPName id, HsExpr id pat)] -> SDoc
438 pp_ipbinds pairs = hsep (punctuate semi (map pp_item pairs))
440 pp_item (id,rhs) = ppr id <+> equals <+> ppr_expr rhs
444 %************************************************************************
446 \subsection{@Match@, @GRHSs@, and @GRHS@ datatypes}
448 %************************************************************************
450 @Match@es are sets of pattern bindings and right hand sides for
451 functions, patterns or case branches. For example, if a function @g@
457 then \tr{g} has two @Match@es: @(x,y) = y@ and @((x:ys),y) = y+1@.
459 It is always the case that each element of an @[Match]@ list has the
460 same number of @pats@s inside it. This corresponds to saying that
461 a function defined by pattern matching must have the same number of
462 patterns in each equation.
467 [pat] -- The patterns
468 (Maybe (HsType id)) -- A type signature for the result of the match
469 -- Nothing after typechecking
473 -- GRHSs are used both for pattern bindings and for Matches
475 = GRHSs [GRHS id pat] -- Guarded RHSs
476 (HsBinds id pat) -- The where clause
477 PostTcType -- Type of RHS (after type checking)
480 = GRHS [Stmt id pat] -- The RHS is the final ResultStmt
481 -- I considered using a RetunStmt, but
482 -- it printed 'wrong' in error messages
485 mkSimpleMatch :: [pat] -> HsExpr id pat -> Type -> SrcLoc -> Match id pat
486 mkSimpleMatch pats rhs rhs_ty locn
487 = Match pats Nothing (GRHSs (unguardedRHS rhs locn) EmptyBinds rhs_ty)
489 unguardedRHS :: HsExpr id pat -> SrcLoc -> [GRHS id pat]
490 unguardedRHS rhs loc = [GRHS [ResultStmt rhs loc] loc]
493 @getMatchLoc@ takes a @Match@ and returns the
494 source-location gotten from the GRHS inside.
495 THis is something of a nuisance, but no more.
498 getMatchLoc :: Match id pat -> SrcLoc
499 getMatchLoc (Match _ _ (GRHSs (GRHS _ loc : _) _ _)) = loc
502 We know the list must have at least one @Match@ in it.
505 pprMatches :: (Outputable id, Outputable pat)
506 => HsMatchContext id -> [Match id pat] -> SDoc
507 pprMatches ctxt matches = vcat (map (pprMatch ctxt) matches)
509 -- Exported to HsBinds, which can't see the defn of HsMatchContext
510 pprFunBind :: (Outputable id, Outputable pat)
511 => id -> [Match id pat] -> SDoc
512 pprFunBind fun matches = pprMatches (FunRhs fun) matches
514 -- Exported to HsBinds, which can't see the defn of HsMatchContext
515 pprPatBind :: (Outputable id, Outputable pat)
516 => pat -> GRHSs id pat -> SDoc
517 pprPatBind pat grhss = sep [ppr pat, nest 4 (pprGRHSs PatBindRhs grhss)]
520 pprMatch :: (Outputable id, Outputable pat)
521 => HsMatchContext id -> Match id pat -> SDoc
522 pprMatch ctxt (Match pats maybe_ty grhss)
523 = pp_name ctxt <+> sep [sep (map ppr pats),
525 nest 2 (pprGRHSs ctxt grhss)]
527 pp_name (FunRhs fun) = ppr fun
528 pp_name other = empty
529 ppr_maybe_ty = case maybe_ty of
530 Just ty -> dcolon <+> ppr ty
534 pprGRHSs :: (Outputable id, Outputable pat)
535 => HsMatchContext id -> GRHSs id pat -> SDoc
536 pprGRHSs ctxt (GRHSs grhss binds ty)
537 = vcat (map (pprGRHS ctxt) grhss)
539 (if nullBinds binds then empty
540 else text "where" $$ nest 4 (pprDeeper (ppr binds)))
543 pprGRHS :: (Outputable id, Outputable pat)
544 => HsMatchContext id -> GRHS id pat -> SDoc
546 pprGRHS ctxt (GRHS [ResultStmt expr _] locn)
549 pprGRHS ctxt (GRHS guarded locn)
550 = sep [char '|' <+> interpp'SP guards, pp_rhs ctxt expr]
552 ResultStmt expr _ = last guarded -- Last stmt should be a ResultStmt for guards
553 guards = init guarded
555 pp_rhs ctxt rhs = ptext (matchSeparator ctxt) <+> pprDeeper (ppr rhs)
560 %************************************************************************
562 \subsection{Do stmts and list comprehensions}
564 %************************************************************************
568 = BindStmt pat (HsExpr id pat) SrcLoc
569 | LetStmt (HsBinds id pat)
570 | ResultStmt (HsExpr id pat) SrcLoc -- See notes that follow
571 | ExprStmt (HsExpr id pat) PostTcType SrcLoc -- See notes that follow
572 -- The type is the *element type* of the expression
573 | ParStmt [[Stmt id pat]] -- List comp only: parallel set of quals
574 | ParStmtOut [([id], [Stmt id pat])] -- PLC after renaming; the ids are the binders
575 -- bound by the stmts
578 ExprStmts and ResultStmts are a bit tricky, because what they mean
579 depends on the context. Consider the following contexts:
581 A do expression of type (m res_ty)
582 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
583 * ExprStmt E any_ty: do { ....; E; ... }
585 Translation: E >> ...
587 * ResultStmt E: do { ....; E }
591 A list comprehensions of type [elt_ty]
592 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
593 * ExprStmt E Bool: [ .. | .... E ]
595 [ .. | .... | ..., E | ... ]
597 Translation: if E then fail else ...
599 * ResultStmt E: [ E | ... ]
601 Translation: return E
603 A guard list, guarding a RHS of type rhs_ty
604 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
605 * ExprStmt E Bool: f x | ..., E, ... = ...rhs...
607 Translation: if E then fail else ...
609 * ResultStmt E: f x | ...guards... = E
613 Array comprehensions are handled like list comprehensions -=chak
616 consLetStmt :: HsBinds id pat -> [Stmt id pat] -> [Stmt id pat]
617 consLetStmt EmptyBinds stmts = stmts
618 consLetStmt binds stmts = LetStmt binds : stmts
622 instance (Outputable id, Outputable pat) =>
623 Outputable (Stmt id pat) where
624 ppr stmt = pprStmt stmt
626 pprStmt (BindStmt pat expr _) = hsep [ppr pat, ptext SLIT("<-"), ppr expr]
627 pprStmt (LetStmt binds) = hsep [ptext SLIT("let"), pprBinds binds]
628 pprStmt (ExprStmt expr _ _) = ppr expr
629 pprStmt (ResultStmt expr _) = ppr expr
630 pprStmt (ParStmt stmtss)
631 = hsep (map (\stmts -> ptext SLIT("| ") <> ppr stmts) stmtss)
632 pprStmt (ParStmtOut stmtss)
633 = hsep (map (\stmts -> ptext SLIT("| ") <> ppr stmts) stmtss)
635 pprDo :: (Outputable id, Outputable pat)
636 => HsDoContext -> [Stmt id pat] -> SDoc
637 pprDo DoExpr stmts = hang (ptext SLIT("do")) 2 (vcat (map ppr stmts))
638 pprDo ListComp stmts = pprComp brackets stmts
639 pprDo PArrComp stmts = pprComp pabrackets stmts
641 pprComp :: (Outputable id, Outputable pat)
642 => (SDoc -> SDoc) -> [Stmt id pat] -> SDoc
643 pprComp brack stmts = brack $
644 hang (pprExpr expr <+> char '|')
647 ResultStmt expr _ = last stmts -- Last stmt should
648 quals = init stmts -- be an ResultStmt
651 %************************************************************************
653 \subsection{Enumerations and list comprehensions}
655 %************************************************************************
658 data ArithSeqInfo id pat
659 = From (HsExpr id pat)
660 | FromThen (HsExpr id pat)
662 | FromTo (HsExpr id pat)
664 | FromThenTo (HsExpr id pat)
670 instance (Outputable id, Outputable pat) =>
671 Outputable (ArithSeqInfo id pat) where
672 ppr (From e1) = hcat [ppr e1, pp_dotdot]
673 ppr (FromThen e1 e2) = hcat [ppr e1, comma, space, ppr e2, pp_dotdot]
674 ppr (FromTo e1 e3) = hcat [ppr e1, pp_dotdot, ppr e3]
675 ppr (FromThenTo e1 e2 e3)
676 = hcat [ppr e1, comma, space, ppr e2, pp_dotdot, ppr e3]
678 pp_dotdot = ptext SLIT(" .. ")
682 %************************************************************************
684 \subsection{HsMatchCtxt}
686 %************************************************************************
689 data HsMatchContext id -- Context of a Match or Stmt
690 = DoCtxt HsDoContext -- Do-stmt or list comprehension
691 | FunRhs id -- Function binding for f
692 | CaseAlt -- Guard on a case alternative
693 | LambdaExpr -- Lambda
694 | PatBindRhs -- Pattern binding
695 | RecUpd -- Record update
698 data HsDoContext = ListComp
700 | PArrComp -- parallel array comprehension
704 isDoExpr (DoCtxt DoExpr) = True
705 isDoExpr other = False
709 matchSeparator (FunRhs _) = SLIT("=")
710 matchSeparator CaseAlt = SLIT("->")
711 matchSeparator LambdaExpr = SLIT("->")
712 matchSeparator PatBindRhs = SLIT("=")
713 matchSeparator (DoCtxt _) = SLIT("<-")
714 matchSeparator RecUpd = panic "When is this used?"
718 pprMatchContext (FunRhs fun) = ptext SLIT("In the definition of") <+> quotes (ppr fun)
719 pprMatchContext CaseAlt = ptext SLIT("In a case alternative")
720 pprMatchContext RecUpd = ptext SLIT("In a record-update construct")
721 pprMatchContext PatBindRhs = ptext SLIT("In a pattern binding")
722 pprMatchContext LambdaExpr = ptext SLIT("In a lambda abstraction")
723 pprMatchContext (DoCtxt DoExpr) = ptext SLIT("In a 'do' expression pattern binding")
724 pprMatchContext (DoCtxt ListComp) =
725 ptext SLIT("In a 'list comprehension' pattern binding")
726 pprMatchContext (DoCtxt PArrComp) =
727 ptext SLIT("In an 'array comprehension' pattern binding")
729 -- Used to generate the string for a *runtime* error message
730 matchContextErrString (FunRhs fun) = "function " ++ showSDoc (ppr fun)
731 matchContextErrString CaseAlt = "case"
732 matchContextErrString PatBindRhs = "pattern binding"
733 matchContextErrString RecUpd = "record update"
734 matchContextErrString LambdaExpr = "lambda"
735 matchContextErrString (DoCtxt DoExpr) = "'do' expression"
736 matchContextErrString (DoCtxt ListComp) = "list comprehension"
737 matchContextErrString (DoCtxt PArrComp) = "array comprehension"