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 [id] -- Dicts needed for construction
134 (HsRecordBinds id pat)
136 | ExprWithTySig -- signature binding
139 | ArithSeqIn -- arithmetic sequence
140 (ArithSeqInfo id pat)
142 (HsExpr id pat) -- (typechecked, of course)
143 (ArithSeqInfo id pat)
144 | PArrSeqIn -- arith. sequence for parallel array
145 (ArithSeqInfo id pat) -- [:e1..e2:] or [:e1, e2..e3:]
147 (HsExpr id pat) -- (typechecked, of course)
148 (ArithSeqInfo id pat)
150 | HsCCall CLabelString -- call into the C world; string is
151 [HsExpr id pat] -- the C function; exprs are the
152 -- arguments to pass.
153 Safety -- True <=> might cause Haskell
154 -- garbage-collection (must generate
155 -- more paranoid code)
156 Bool -- True <=> it's really a "casm"
157 -- NOTE: this CCall is the *boxed*
158 -- version; the desugarer will convert
159 -- it into the unboxed "ccall#".
160 PostTcType -- The result type; will be *bottom*
161 -- until the typechecker gets ahold of it
163 | HsSCC FAST_STRING -- "set cost centre" (_scc_) annotation
164 (HsExpr id pat) -- expr whose cost is to be measured
168 These constructors only appear temporarily in the parser.
169 The renamer translates them into the Right Thing.
172 | EWildPat -- wildcard
174 | EAsPat id -- as pattern
177 | ELazyPat (HsExpr id pat) -- ~ pattern
179 | HsType (HsType id) -- Explicit type argument; e.g f {| Int |} x y
182 Everything from here on appears only in typechecker output.
185 | TyLam -- TRANSLATION
188 | TyApp -- TRANSLATION
189 (HsExpr id pat) -- generated by Spec
192 -- DictLam and DictApp are "inverses"
200 type HsRecordBinds id pat
201 = [(id, HsExpr id pat, Bool)]
202 -- True <=> source code used "punning",
203 -- i.e. {op1, op2} rather than {op1=e1, op2=e2}
206 A @Dictionary@, unless of length 0 or 1, becomes a tuple. A
207 @ClassDictLam dictvars methods expr@ is, therefore:
209 \ x -> case x of ( dictvars-and-methods-tuple ) -> expr
213 instance (Outputable id, Outputable pat) =>
214 Outputable (HsExpr id pat) where
215 ppr expr = pprExpr expr
219 pprExpr :: (Outputable id, Outputable pat)
220 => HsExpr id pat -> SDoc
222 pprExpr e = pprDeeper (ppr_expr e)
223 pprBinds b = pprDeeper (ppr b)
226 -- Put it in parens if it's an operator
227 | isOperator v = parens (ppr v)
230 ppr_expr (HsIPVar v) = ppr v
231 ppr_expr (HsLit lit) = ppr lit
232 ppr_expr (HsOverLit lit) = ppr lit
234 ppr_expr (HsLam match)
235 = hsep [char '\\', nest 2 (pprMatch LambdaExpr match)]
237 ppr_expr expr@(HsApp e1 e2)
238 = let (fun, args) = collect_args expr [] in
239 (ppr_expr fun) <+> (sep (map ppr_expr args))
241 collect_args (HsApp fun arg) args = collect_args fun (arg:args)
242 collect_args fun args = (fun, args)
244 ppr_expr (OpApp e1 op fixity e2)
246 HsVar v -> pp_infixly v
249 pp_e1 = pprParendExpr e1 -- Add parens to make precedence clear
250 pp_e2 = pprParendExpr e2
253 = hang (pprExpr op) 4 (sep [pp_e1, pp_e2])
256 = sep [pp_e1, hsep [pp_v_op, pp_e2]]
258 pp_v_op | isOperator v = ppr v
259 | otherwise = char '`' <> ppr v <> char '`'
260 -- Put it in backquotes if it's not an operator already
262 ppr_expr (NegApp e _) = char '-' <+> pprParendExpr e
264 ppr_expr (HsPar e) = parens (ppr_expr e)
266 ppr_expr (SectionL expr op)
268 HsVar v -> pp_infixly v
271 pp_expr = pprParendExpr expr
273 pp_prefixly = hang (hsep [text " \\ x_ ->", ppr op])
274 4 (hsep [pp_expr, ptext SLIT("x_ )")])
275 pp_infixly v = parens (sep [pp_expr, ppr v])
277 ppr_expr (SectionR op expr)
279 HsVar v -> pp_infixly v
282 pp_expr = pprParendExpr expr
284 pp_prefixly = hang (hsep [text "( \\ x_ ->", ppr op, ptext SLIT("x_")])
285 4 ((<>) pp_expr rparen)
287 = parens (sep [ppr v, pp_expr])
289 ppr_expr (HsCase expr matches _)
290 = sep [ sep [ptext SLIT("case"), nest 4 (pprExpr expr), ptext SLIT("of")],
291 nest 2 (pprMatches CaseAlt matches) ]
293 ppr_expr (HsIf e1 e2 e3 _)
294 = sep [hsep [ptext SLIT("if"), nest 2 (pprExpr e1), ptext SLIT("then")],
299 -- special case: let ... in let ...
300 ppr_expr (HsLet binds expr@(HsLet _ _))
301 = sep [hang (ptext SLIT("let")) 2 (hsep [pprBinds binds, ptext SLIT("in")]),
304 ppr_expr (HsLet binds expr)
305 = sep [hang (ptext SLIT("let")) 2 (pprBinds binds),
306 hang (ptext SLIT("in")) 2 (ppr expr)]
308 ppr_expr (HsWith expr binds)
309 = hsep [ppr expr, ptext SLIT("with"), pp_ipbinds binds]
311 ppr_expr (HsDo do_or_list_comp stmts _) = pprDo do_or_list_comp stmts
312 ppr_expr (HsDoOut do_or_list_comp stmts _ _ _ _ _) = pprDo do_or_list_comp stmts
314 ppr_expr (ExplicitList _ exprs)
315 = brackets (fsep (punctuate comma (map ppr_expr exprs)))
317 ppr_expr (ExplicitPArr _ exprs)
318 = pabrackets (fsep (punctuate comma (map ppr_expr exprs)))
320 ppr_expr (ExplicitTuple exprs boxity)
321 = tupleParens boxity (sep (punctuate comma (map ppr_expr exprs)))
323 ppr_expr (RecordCon con_id rbinds)
324 = pp_rbinds (ppr con_id) rbinds
325 ppr_expr (RecordConOut data_con con rbinds)
326 = pp_rbinds (ppr con) rbinds
328 ppr_expr (RecordUpd aexp rbinds)
329 = pp_rbinds (pprParendExpr aexp) rbinds
330 ppr_expr (RecordUpdOut aexp _ _ _ rbinds)
331 = pp_rbinds (pprParendExpr aexp) rbinds
333 ppr_expr (ExprWithTySig expr sig)
334 = hang (nest 2 (ppr_expr expr) <+> dcolon)
337 ppr_expr (ArithSeqIn info)
338 = brackets (ppr info)
339 ppr_expr (ArithSeqOut expr info)
340 = brackets (ppr info)
342 ppr_expr (PArrSeqIn info)
343 = pabrackets (ppr info)
344 ppr_expr (PArrSeqOut expr info)
345 = pabrackets (ppr info)
347 ppr_expr EWildPat = char '_'
348 ppr_expr (ELazyPat e) = char '~' <> pprParendExpr e
349 ppr_expr (EAsPat v e) = ppr v <> char '@' <> pprParendExpr e
351 ppr_expr (HsCCall fun args _ is_asm result_ty)
353 then ptext SLIT("_casm_ ``") <> pprCLabelString fun <> ptext SLIT("''")
354 else ptext SLIT("_ccall_") <+> pprCLabelString fun)
355 4 (sep (map pprParendExpr args))
357 ppr_expr (HsSCC lbl expr)
358 = sep [ ptext SLIT("_scc_") <+> doubleQuotes (ptext lbl), pprParendExpr expr ]
360 ppr_expr (TyLam tyvars expr)
361 = hang (hsep [ptext SLIT("/\\"), interppSP tyvars, ptext SLIT("->")])
364 ppr_expr (TyApp expr [ty])
365 = hang (ppr_expr expr) 4 (pprParendType ty)
367 ppr_expr (TyApp expr tys)
368 = hang (ppr_expr expr)
369 4 (brackets (interpp'SP tys))
371 ppr_expr (DictLam dictvars expr)
372 = hang (hsep [ptext SLIT("\\{-dict-}"), interppSP dictvars, ptext SLIT("->")])
375 ppr_expr (DictApp expr [dname])
376 = hang (ppr_expr expr) 4 (ppr dname)
378 ppr_expr (DictApp expr dnames)
379 = hang (ppr_expr expr)
380 4 (brackets (interpp'SP dnames))
382 ppr_expr (HsType id) = ppr id
384 -- add parallel array brackets around a document
386 pabrackets :: SDoc -> SDoc
387 pabrackets p = ptext SLIT("[:") <> p <> ptext SLIT(":]")
390 Parenthesize unless very simple:
392 pprParendExpr :: (Outputable id, Outputable pat)
393 => HsExpr id pat -> SDoc
397 pp_as_was = pprExpr expr
404 HsIPVar _ -> pp_as_was
405 ExplicitList _ _ -> pp_as_was
406 ExplicitPArr _ _ -> pp_as_was
407 ExplicitTuple _ _ -> pp_as_was
410 _ -> parens pp_as_was
413 %************************************************************************
415 \subsection{Record binds}
417 %************************************************************************
420 pp_rbinds :: (Outputable id, Outputable pat)
422 -> HsRecordBinds id pat -> SDoc
424 pp_rbinds thing rbinds
426 4 (braces (sep (punctuate comma (map (pp_rbind) rbinds))))
428 pp_rbind (v, e, pun_flag)
429 = getPprStyle $ \ sty ->
430 if pun_flag && userStyle sty then
433 hsep [ppr v, char '=', ppr e]
437 pp_ipbinds :: (Outputable id, Outputable pat)
438 => [(IPName id, HsExpr id pat)] -> SDoc
439 pp_ipbinds pairs = hsep (punctuate semi (map pp_item pairs))
441 pp_item (id,rhs) = ppr id <+> equals <+> ppr_expr rhs
445 %************************************************************************
447 \subsection{@Match@, @GRHSs@, and @GRHS@ datatypes}
449 %************************************************************************
451 @Match@es are sets of pattern bindings and right hand sides for
452 functions, patterns or case branches. For example, if a function @g@
458 then \tr{g} has two @Match@es: @(x,y) = y@ and @((x:ys),y) = y+1@.
460 It is always the case that each element of an @[Match]@ list has the
461 same number of @pats@s inside it. This corresponds to saying that
462 a function defined by pattern matching must have the same number of
463 patterns in each equation.
468 [pat] -- The patterns
469 (Maybe (HsType id)) -- A type signature for the result of the match
470 -- Nothing after typechecking
474 -- GRHSs are used both for pattern bindings and for Matches
476 = GRHSs [GRHS id pat] -- Guarded RHSs
477 (HsBinds id pat) -- The where clause
478 PostTcType -- Type of RHS (after type checking)
481 = GRHS [Stmt id pat] -- The RHS is the final ResultStmt
482 -- I considered using a RetunStmt, but
483 -- it printed 'wrong' in error messages
486 mkSimpleMatch :: [pat] -> HsExpr id pat -> Type -> SrcLoc -> Match id pat
487 mkSimpleMatch pats rhs rhs_ty locn
488 = Match pats Nothing (GRHSs (unguardedRHS rhs locn) EmptyBinds rhs_ty)
490 unguardedRHS :: HsExpr id pat -> SrcLoc -> [GRHS id pat]
491 unguardedRHS rhs loc = [GRHS [ResultStmt rhs loc] loc]
494 @getMatchLoc@ takes a @Match@ and returns the
495 source-location gotten from the GRHS inside.
496 THis is something of a nuisance, but no more.
499 getMatchLoc :: Match id pat -> SrcLoc
500 getMatchLoc (Match _ _ (GRHSs (GRHS _ loc : _) _ _)) = loc
503 We know the list must have at least one @Match@ in it.
506 pprMatches :: (Outputable id, Outputable pat)
507 => HsMatchContext id -> [Match id pat] -> SDoc
508 pprMatches ctxt matches = vcat (map (pprMatch ctxt) matches)
510 -- Exported to HsBinds, which can't see the defn of HsMatchContext
511 pprFunBind :: (Outputable id, Outputable pat)
512 => id -> [Match id pat] -> SDoc
513 pprFunBind fun matches = pprMatches (FunRhs fun) matches
515 -- Exported to HsBinds, which can't see the defn of HsMatchContext
516 pprPatBind :: (Outputable id, Outputable pat)
517 => pat -> GRHSs id pat -> SDoc
518 pprPatBind pat grhss = sep [ppr pat, nest 4 (pprGRHSs PatBindRhs grhss)]
521 pprMatch :: (Outputable id, Outputable pat)
522 => HsMatchContext id -> Match id pat -> SDoc
523 pprMatch ctxt (Match pats maybe_ty grhss)
524 = pp_name ctxt <+> sep [sep (map ppr pats),
526 nest 2 (pprGRHSs ctxt grhss)]
528 pp_name (FunRhs fun) = ppr fun
529 pp_name other = empty
530 ppr_maybe_ty = case maybe_ty of
531 Just ty -> dcolon <+> ppr ty
535 pprGRHSs :: (Outputable id, Outputable pat)
536 => HsMatchContext id -> GRHSs id pat -> SDoc
537 pprGRHSs ctxt (GRHSs grhss binds ty)
538 = vcat (map (pprGRHS ctxt) grhss)
540 (if nullBinds binds then empty
541 else text "where" $$ nest 4 (pprDeeper (ppr binds)))
544 pprGRHS :: (Outputable id, Outputable pat)
545 => HsMatchContext id -> GRHS id pat -> SDoc
547 pprGRHS ctxt (GRHS [ResultStmt expr _] locn)
550 pprGRHS ctxt (GRHS guarded locn)
551 = sep [char '|' <+> interpp'SP guards, pp_rhs ctxt expr]
553 ResultStmt expr _ = last guarded -- Last stmt should be a ResultStmt for guards
554 guards = init guarded
556 pp_rhs ctxt rhs = ptext (matchSeparator ctxt) <+> pprDeeper (ppr rhs)
561 %************************************************************************
563 \subsection{Do stmts and list comprehensions}
565 %************************************************************************
569 = BindStmt pat (HsExpr id pat) SrcLoc
570 | LetStmt (HsBinds id pat)
571 | ResultStmt (HsExpr id pat) SrcLoc -- See notes that follow
572 | ExprStmt (HsExpr id pat) PostTcType SrcLoc -- See notes that follow
573 -- The type is the *element type* of the expression
574 | ParStmt [[Stmt id pat]] -- List comp only: parallel set of quals
575 | ParStmtOut [([id], [Stmt id pat])] -- PLC after renaming; the ids are the binders
576 -- bound by the stmts
579 ExprStmts and ResultStmts are a bit tricky, because what they mean
580 depends on the context. Consider the following contexts:
582 A do expression of type (m res_ty)
583 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
584 * ExprStmt E any_ty: do { ....; E; ... }
586 Translation: E >> ...
588 * ResultStmt E: do { ....; E }
592 A list comprehensions of type [elt_ty]
593 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
594 * ExprStmt E Bool: [ .. | .... E ]
596 [ .. | .... | ..., E | ... ]
598 Translation: if E then fail else ...
600 * ResultStmt E: [ E | ... ]
602 Translation: return E
604 A guard list, guarding a RHS of type rhs_ty
605 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
606 * ExprStmt E Bool: f x | ..., E, ... = ...rhs...
608 Translation: if E then fail else ...
610 * ResultStmt E: f x | ...guards... = E
614 Array comprehensions are handled like list comprehensions -=chak
617 consLetStmt :: HsBinds id pat -> [Stmt id pat] -> [Stmt id pat]
618 consLetStmt EmptyBinds stmts = stmts
619 consLetStmt binds stmts = LetStmt binds : stmts
623 instance (Outputable id, Outputable pat) =>
624 Outputable (Stmt id pat) where
625 ppr stmt = pprStmt stmt
627 pprStmt (BindStmt pat expr _) = hsep [ppr pat, ptext SLIT("<-"), ppr expr]
628 pprStmt (LetStmt binds) = hsep [ptext SLIT("let"), pprBinds binds]
629 pprStmt (ExprStmt expr _ _) = ppr expr
630 pprStmt (ResultStmt expr _) = ppr expr
631 pprStmt (ParStmt stmtss)
632 = hsep (map (\stmts -> ptext SLIT("| ") <> ppr stmts) stmtss)
633 pprStmt (ParStmtOut stmtss)
634 = hsep (map (\stmts -> ptext SLIT("| ") <> ppr stmts) stmtss)
636 pprDo :: (Outputable id, Outputable pat)
637 => HsDoContext -> [Stmt id pat] -> SDoc
638 pprDo DoExpr stmts = hang (ptext SLIT("do")) 2 (vcat (map ppr stmts))
639 pprDo ListComp stmts = pprComp brackets stmts
640 pprDo PArrComp stmts = pprComp pabrackets stmts
642 pprComp :: (Outputable id, Outputable pat)
643 => (SDoc -> SDoc) -> [Stmt id pat] -> SDoc
644 pprComp brack stmts = brack $
645 hang (pprExpr expr <+> char '|')
648 ResultStmt expr _ = last stmts -- Last stmt should
649 quals = init stmts -- be an ResultStmt
652 %************************************************************************
654 \subsection{Enumerations and list comprehensions}
656 %************************************************************************
659 data ArithSeqInfo id pat
660 = From (HsExpr id pat)
661 | FromThen (HsExpr id pat)
663 | FromTo (HsExpr id pat)
665 | FromThenTo (HsExpr id pat)
671 instance (Outputable id, Outputable pat) =>
672 Outputable (ArithSeqInfo id pat) where
673 ppr (From e1) = hcat [ppr e1, pp_dotdot]
674 ppr (FromThen e1 e2) = hcat [ppr e1, comma, space, ppr e2, pp_dotdot]
675 ppr (FromTo e1 e3) = hcat [ppr e1, pp_dotdot, ppr e3]
676 ppr (FromThenTo e1 e2 e3)
677 = hcat [ppr e1, comma, space, ppr e2, pp_dotdot, ppr e3]
679 pp_dotdot = ptext SLIT(" .. ")
683 %************************************************************************
685 \subsection{HsMatchCtxt}
687 %************************************************************************
690 data HsMatchContext id -- Context of a Match or Stmt
691 = DoCtxt HsDoContext -- Do-stmt or list comprehension
692 | FunRhs id -- Function binding for f
693 | CaseAlt -- Guard on a case alternative
694 | LambdaExpr -- Lambda
695 | PatBindRhs -- Pattern binding
696 | RecUpd -- Record update
699 data HsDoContext = ListComp
701 | PArrComp -- parallel array comprehension
705 isDoExpr (DoCtxt DoExpr) = True
706 isDoExpr other = False
710 matchSeparator (FunRhs _) = SLIT("=")
711 matchSeparator CaseAlt = SLIT("->")
712 matchSeparator LambdaExpr = SLIT("->")
713 matchSeparator PatBindRhs = SLIT("=")
714 matchSeparator (DoCtxt _) = SLIT("<-")
715 matchSeparator RecUpd = panic "When is this used?"
719 pprMatchContext (FunRhs fun) = ptext SLIT("In the definition of") <+> quotes (ppr fun)
720 pprMatchContext CaseAlt = ptext SLIT("In a case alternative")
721 pprMatchContext RecUpd = ptext SLIT("In a record-update construct")
722 pprMatchContext PatBindRhs = ptext SLIT("In a pattern binding")
723 pprMatchContext LambdaExpr = ptext SLIT("In a lambda abstraction")
724 pprMatchContext (DoCtxt DoExpr) = ptext SLIT("In a 'do' expression pattern binding")
725 pprMatchContext (DoCtxt ListComp) =
726 ptext SLIT("In a 'list comprehension' pattern binding")
727 pprMatchContext (DoCtxt PArrComp) =
728 ptext SLIT("In an 'array comprehension' pattern binding")
730 -- Used to generate the string for a *runtime* error message
731 matchContextErrString (FunRhs fun) = "function " ++ showSDoc (ppr fun)
732 matchContextErrString CaseAlt = "case"
733 matchContextErrString PatBindRhs = "pattern binding"
734 matchContextErrString RecUpd = "record update"
735 matchContextErrString LambdaExpr = "lambda"
736 matchContextErrString (DoCtxt DoExpr) = "'do' expression"
737 matchContextErrString (DoCtxt ListComp) = "list comprehension"
738 matchContextErrString (DoCtxt PArrComp) = "array comprehension"