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 )
21 import PprType ( pprParendType )
24 import DataCon ( DataCon )
25 import CStrings ( CLabelString, pprCLabelString )
26 import BasicTypes ( Boxity, tupleParens )
27 import SrcLoc ( SrcLoc )
30 %************************************************************************
32 \subsection{Expressions proper}
34 %************************************************************************
38 = HsVar id -- variable
39 | HsIPVar id -- implicit parameter
40 | HsOverLit HsOverLit -- Overloaded literals; eliminated by type checker
41 | HsLit HsLit -- Simple (non-overloaded) literals
43 | HsLam (Match id pat) -- lambda
44 | HsApp (HsExpr id pat) -- application
47 -- Operator applications:
48 -- NB Bracketed ops such as (+) come out as Vars.
50 -- NB We need an expr for the operator in an OpApp/Section since
51 -- the typechecker may need to apply the operator to a few types.
53 | OpApp (HsExpr id pat) -- left operand
54 (HsExpr id pat) -- operator
55 Fixity -- Renamer adds fixity; bottom until then
56 (HsExpr id pat) -- right operand
58 -- We preserve prefix negation and parenthesis for the precedence parser.
59 -- They are eventually removed by the type checker.
61 | NegApp (HsExpr id pat) -- negated expr
63 | HsPar (HsExpr id pat) -- parenthesised expr
65 | SectionL (HsExpr id pat) -- operand
66 (HsExpr id pat) -- operator
67 | SectionR (HsExpr id pat) -- operator
68 (HsExpr id pat) -- operand
70 | HsCase (HsExpr id pat)
74 | HsIf (HsExpr id pat) -- predicate
75 (HsExpr id pat) -- then part
76 (HsExpr id pat) -- else part
79 | HsLet (HsBinds id pat) -- let(rec)
82 | HsWith (HsExpr id pat) -- implicit parameter binding
86 [Stmt id pat] -- "do":one or more stmts
89 | HsDoOut HsMatchContext
90 [Stmt id pat] -- "do":one or more stmts
94 Type -- Type of the whole expression
97 | ExplicitList -- syntactic list
99 | ExplicitListOut -- TRANSLATION
100 Type -- Gives type of components of list
103 | ExplicitTuple -- tuple
105 -- NB: Unit is ExplicitTuple []
106 -- for tuples, we can get the types
107 -- direct from the components
111 -- Record construction
112 | RecordCon id -- The constructor
113 (HsRecordBinds id pat)
115 | RecordConOut DataCon
116 (HsExpr id pat) -- Data con Id applied to type args
117 (HsRecordBinds id pat)
121 | RecordUpd (HsExpr id pat)
122 (HsRecordBinds id pat)
124 | RecordUpdOut (HsExpr id pat) -- TRANSLATION
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 Bool -- 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 Type -- 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 (True,empty) 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 (True, empty) 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)))
305 ppr_expr (ExplicitListOut ty exprs)
306 = brackets (fsep (punctuate comma (map ppr_expr exprs)))
308 ppr_expr (ExplicitTuple exprs boxity)
309 = tupleParens boxity (sep (punctuate comma (map ppr_expr exprs)))
311 ppr_expr (RecordCon con_id rbinds)
312 = pp_rbinds (ppr con_id) rbinds
313 ppr_expr (RecordConOut data_con con rbinds)
314 = pp_rbinds (ppr con) rbinds
316 ppr_expr (RecordUpd aexp rbinds)
317 = pp_rbinds (pprParendExpr aexp) rbinds
318 ppr_expr (RecordUpdOut aexp _ _ rbinds)
319 = pp_rbinds (pprParendExpr aexp) rbinds
321 ppr_expr (ExprWithTySig expr sig)
322 = hang (nest 2 (ppr_expr expr) <+> dcolon)
325 ppr_expr (ArithSeqIn info)
326 = brackets (ppr info)
327 ppr_expr (ArithSeqOut expr info)
328 = brackets (ppr info)
330 ppr_expr EWildPat = char '_'
331 ppr_expr (ELazyPat e) = char '~' <> pprParendExpr e
332 ppr_expr (EAsPat v e) = ppr v <> char '@' <> pprParendExpr e
334 ppr_expr (HsCCall fun args _ is_asm result_ty)
336 then ptext SLIT("_casm_ ``") <> pprCLabelString fun <> ptext SLIT("''")
337 else ptext SLIT("_ccall_") <+> pprCLabelString fun)
338 4 (sep (map pprParendExpr args))
340 ppr_expr (HsSCC lbl expr)
341 = sep [ ptext SLIT("_scc_") <+> doubleQuotes (ptext lbl), pprParendExpr expr ]
343 ppr_expr (TyLam tyvars expr)
344 = hang (hsep [ptext SLIT("/\\"), interppSP tyvars, ptext SLIT("->")])
347 ppr_expr (TyApp expr [ty])
348 = hang (ppr_expr expr) 4 (pprParendType ty)
350 ppr_expr (TyApp expr tys)
351 = hang (ppr_expr expr)
352 4 (brackets (interpp'SP tys))
354 ppr_expr (DictLam dictvars expr)
355 = hang (hsep [ptext SLIT("\\{-dict-}"), interppSP dictvars, ptext SLIT("->")])
358 ppr_expr (DictApp expr [dname])
359 = hang (ppr_expr expr) 4 (ppr dname)
361 ppr_expr (DictApp expr dnames)
362 = hang (ppr_expr expr)
363 4 (brackets (interpp'SP dnames))
365 ppr_expr (HsType id) = ppr id
369 Parenthesize unless very simple:
371 pprParendExpr :: (Outputable id, Outputable pat)
372 => HsExpr id pat -> SDoc
376 pp_as_was = pprExpr expr
383 HsIPVar _ -> pp_as_was
384 ExplicitList _ -> pp_as_was
385 ExplicitListOut _ _ -> pp_as_was
386 ExplicitTuple _ _ -> pp_as_was
389 _ -> parens pp_as_was
392 %************************************************************************
394 \subsection{Record binds}
396 %************************************************************************
399 pp_rbinds :: (Outputable id, Outputable pat)
401 -> HsRecordBinds id pat -> SDoc
403 pp_rbinds thing rbinds
405 4 (braces (sep (punctuate comma (map (pp_rbind) rbinds))))
407 pp_rbind (v, e, pun_flag)
408 = getPprStyle $ \ sty ->
409 if pun_flag && userStyle sty then
412 hsep [ppr v, char '=', ppr e]
417 %************************************************************************
419 \subsection{@Match@, @GRHSs@, and @GRHS@ datatypes}
421 %************************************************************************
423 @Match@es are sets of pattern bindings and right hand sides for
424 functions, patterns or case branches. For example, if a function @g@
430 then \tr{g} has two @Match@es: @(x,y) = y@ and @((x:ys),y) = y+1@.
432 It is always the case that each element of an @[Match]@ list has the
433 same number of @pats@s inside it. This corresponds to saying that
434 a function defined by pattern matching must have the same number of
435 patterns in each equation.
440 [id] -- Tyvars wrt which this match is universally quantified
441 -- empty after typechecking
442 [pat] -- The patterns
443 (Maybe (HsType id)) -- A type signature for the result of the match
444 -- Nothing after typechecking
448 -- GRHSs are used both for pattern bindings and for Matches
450 = GRHSs [GRHS id pat] -- Guarded RHSs
451 (HsBinds id pat) -- The where clause
452 (Maybe Type) -- Just rhs_ty after type checking
455 = GRHS [Stmt id pat] -- The RHS is the final ExprStmt
456 -- I considered using a RetunStmt, but
457 -- it printed 'wrong' in error messages
460 mkSimpleMatch :: [pat] -> HsExpr id pat -> Maybe Type -> SrcLoc -> Match id pat
461 mkSimpleMatch pats rhs maybe_rhs_ty locn
462 = Match [] pats Nothing (GRHSs (unguardedRHS rhs locn) EmptyBinds maybe_rhs_ty)
464 unguardedRHS :: HsExpr id pat -> SrcLoc -> [GRHS id pat]
465 unguardedRHS rhs loc = [GRHS [ExprStmt rhs loc] loc]
468 @getMatchLoc@ takes a @Match@ and returns the
469 source-location gotten from the GRHS inside.
470 THis is something of a nuisance, but no more.
473 getMatchLoc :: Match id pat -> SrcLoc
474 getMatchLoc (Match _ _ _ (GRHSs (GRHS _ loc : _) _ _)) = loc
477 We know the list must have at least one @Match@ in it.
480 pprMatches :: (Outputable id, Outputable pat)
481 => (Bool, SDoc) -> [Match id pat] -> SDoc
482 pprMatches print_info matches = vcat (map (pprMatch print_info) matches)
485 pprMatch :: (Outputable id, Outputable pat)
486 => (Bool, SDoc) -> Match id pat -> SDoc
487 pprMatch print_info@(is_case, name) (Match _ pats maybe_ty grhss)
488 = maybe_name <+> sep [sep (map ppr pats),
490 nest 2 (pprGRHSs is_case grhss)]
492 maybe_name | is_case = empty
494 ppr_maybe_ty = case maybe_ty of
495 Just ty -> dcolon <+> ppr ty
499 pprGRHSs :: (Outputable id, Outputable pat)
500 => Bool -> GRHSs id pat -> SDoc
501 pprGRHSs is_case (GRHSs grhss binds maybe_ty)
502 = vcat (map (pprGRHS is_case) grhss)
504 (if nullBinds binds then empty
505 else text "where" $$ nest 4 (pprDeeper (ppr binds)))
508 pprGRHS :: (Outputable id, Outputable pat)
509 => Bool -> GRHS id pat -> SDoc
511 pprGRHS is_case (GRHS [ExprStmt expr _] locn)
512 = text (if is_case then "->" else "=") <+> pprDeeper (ppr expr)
514 pprGRHS is_case (GRHS guarded locn)
515 = sep [char '|' <+> interpp'SP guards,
516 text (if is_case then "->" else "=") <+> pprDeeper (ppr expr)
519 ExprStmt expr _ = last guarded -- Last stmt should be a ExprStmt for guards
520 guards = init guarded
525 %************************************************************************
527 \subsection{Do stmts and list comprehensions}
529 %************************************************************************
533 = BindStmt pat (HsExpr id pat) SrcLoc
534 | LetStmt (HsBinds id pat)
535 | ExprStmt (HsExpr id pat) SrcLoc -- See notes that follow
536 | ParStmt [[Stmt id pat]] -- List comp only: parallel set of quals
537 | ParStmtOut [([id], [Stmt id pat])] -- PLC after renaming
540 ExprStmts are a bit tricky, because what
541 they mean depends on the context. Consider
543 in the following contexts:
545 A do expression of type (m res_ty)
546 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
547 * Non-last stmt in list: do { ....; E; ... }
549 Translation: E >> ...
551 * Last stmt in list: do { ....; E }
555 A list comprehensions of type [elt_ty]
556 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
557 * Non-last stmt in list: [ .. | ..., E, ... ]
559 Translation: if E then fail else ...
561 * Last stmt in list: [ E | ... ]
563 Translation: return E
565 A guard list, guarding a RHS of type rhs_ty
566 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
567 * Non-last stmt in list: f x | ..., E, ... = ...rhs...
569 Translation: if E then fail else ...
571 * Last stmt in list: f x | ...guards... = E
576 consLetStmt :: HsBinds id pat -> [Stmt id pat] -> [Stmt id pat]
577 consLetStmt EmptyBinds stmts = stmts
578 consLetStmt binds stmts = LetStmt binds : stmts
582 instance (Outputable id, Outputable pat) =>
583 Outputable (Stmt id pat) where
584 ppr stmt = pprStmt stmt
586 pprStmt (ParStmt stmtss)
587 = hsep (map (\stmts -> ptext SLIT("| ") <> ppr stmts) stmtss)
588 pprStmt (ParStmtOut stmtss)
589 = hsep (map (\stmts -> ptext SLIT("| ") <> ppr stmts) stmtss)
590 pprStmt (BindStmt pat expr _)
591 = hsep [ppr pat, ptext SLIT("<-"), ppr expr]
592 pprStmt (LetStmt binds)
593 = hsep [ptext SLIT("let"), pprBinds binds]
594 pprStmt (ExprStmt expr _)
597 pprDo :: (Outputable id, Outputable pat) => HsMatchContext -> [Stmt id pat] -> SDoc
598 pprDo DoExpr stmts = hang (ptext SLIT("do")) 2 (vcat (map ppr stmts))
599 pprDo ListComp stmts = brackets $
600 hang (pprExpr expr <+> char '|')
603 ExprStmt expr _ = last stmts -- Last stmt should
604 quals = init stmts -- be an ExprStmt
607 %************************************************************************
609 \subsection{Enumerations and list comprehensions}
611 %************************************************************************
614 data ArithSeqInfo id pat
615 = From (HsExpr id pat)
616 | FromThen (HsExpr id pat)
618 | FromTo (HsExpr id pat)
620 | FromThenTo (HsExpr id pat)
626 instance (Outputable id, Outputable pat) =>
627 Outputable (ArithSeqInfo id pat) where
628 ppr (From e1) = hcat [ppr e1, pp_dotdot]
629 ppr (FromThen e1 e2) = hcat [ppr e1, comma, space, ppr e2, pp_dotdot]
630 ppr (FromTo e1 e3) = hcat [ppr e1, pp_dotdot, ppr e3]
631 ppr (FromThenTo e1 e2 e3)
632 = hcat [ppr e1, comma, space, ppr e2, pp_dotdot, ppr e3]
634 pp_dotdot = ptext SLIT(" .. ")
638 %************************************************************************
640 \subsection{HsMatchCtxt}
642 %************************************************************************
645 data HsMatchContext -- Context of a Match or Stmt
646 = ListComp -- List comprehension
647 | DoExpr -- Do Statment
649 | FunRhs Name -- Function binding for f
650 | CaseAlt -- Guard on a case alternative
651 | LambdaExpr -- Lambda
652 | PatBindRhs -- Pattern binding
653 | RecUpd -- Record update
656 -- It's convenient to have FunRhs as a Name
657 -- throughout so that HsMatchContext doesn't
658 -- need to be parameterised.
659 -- In the RdrName world we never use the FunRhs variant.
663 isDoExpr DoExpr = True
664 isDoExpr other = False
666 isDoOrListComp ListComp = True
667 isDoOrListComp DoExpr = True
668 isDoOrListComp other = False
672 matchSeparator (FunRhs _) = SLIT("=")
673 matchSeparator CaseAlt = SLIT("->")
674 matchSeparator LambdaExpr = SLIT("->")
675 matchSeparator PatBindRhs = SLIT("=")
676 matchSeparator DoExpr = SLIT("<-")
677 matchSeparator ListComp = SLIT("<-")
678 matchSeparator RecUpd = panic "When is this used?"
682 pprMatchContext (FunRhs fun) = ptext SLIT("in the definition of function") <+> quotes (ppr fun)
683 pprMatchContext CaseAlt = ptext SLIT("in a group of case alternatives beginning")
684 pprMatchContext RecUpd = ptext SLIT("in a record-update construct")
685 pprMatchContext PatBindRhs = ptext SLIT("in a pattern binding")
686 pprMatchContext LambdaExpr = ptext SLIT("in a lambda abstraction")
687 pprMatchContext DoExpr = ptext SLIT("in a `do' expression pattern binding")
688 pprMatchContext ListComp = ptext SLIT("in a `list comprension' pattern binding")