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 )
18 import Name ( Name, isLexSym )
20 import PprType ( pprParendType )
23 import DataCon ( DataCon )
24 import CStrings ( CLabelString, pprCLabelString )
25 import BasicTypes ( Boxity, tupleParens )
26 import SrcLoc ( SrcLoc )
29 %************************************************************************
31 \subsection{Expressions proper}
33 %************************************************************************
37 = HsVar id -- variable
38 | HsIPVar id -- implicit parameter
39 | HsOverLit HsOverLit -- Overloaded literals; eliminated by type checker
40 | HsLit HsLit -- Simple (non-overloaded) literals
42 | HsLam (Match id pat) -- lambda
43 | HsApp (HsExpr id pat) -- application
46 -- Operator applications:
47 -- NB Bracketed ops such as (+) come out as Vars.
49 -- NB We need an expr for the operator in an OpApp/Section since
50 -- the typechecker may need to apply the operator to a few types.
52 | OpApp (HsExpr id pat) -- left operand
53 (HsExpr id pat) -- operator
54 Fixity -- Renamer adds fixity; bottom until then
55 (HsExpr id pat) -- right operand
57 -- We preserve prefix negation and parenthesis for the precedence parser.
58 -- They are eventually removed by the type checker.
60 | NegApp (HsExpr id pat) -- negated expr
62 | HsPar (HsExpr id pat) -- parenthesised expr
64 | SectionL (HsExpr id pat) -- operand
65 (HsExpr id pat) -- operator
66 | SectionR (HsExpr id pat) -- operator
67 (HsExpr id pat) -- operand
69 | HsCase (HsExpr id pat)
73 | HsIf (HsExpr id pat) -- predicate
74 (HsExpr id pat) -- then part
75 (HsExpr id pat) -- else part
78 | HsLet (HsBinds id pat) -- let(rec)
81 | HsWith (HsExpr id pat) -- implicit parameter binding
85 [Stmt id pat] -- "do":one or more stmts
88 | HsDoOut HsMatchContext
89 [Stmt id pat] -- "do":one or more stmts
93 Type -- Type of the whole expression
96 | ExplicitList -- syntactic list
98 | ExplicitListOut -- TRANSLATION
99 Type -- 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 *result* record (may differ from
125 -- type of input record)
126 [id] -- Dicts needed for construction
127 (HsRecordBinds id pat)
129 | ExprWithTySig -- signature binding
132 | ArithSeqIn -- arithmetic sequence
133 (ArithSeqInfo id pat)
135 (HsExpr id pat) -- (typechecked, of course)
136 (ArithSeqInfo id pat)
138 | HsCCall CLabelString -- call into the C world; string is
139 [HsExpr id pat] -- the C function; exprs are the
140 -- arguments to pass.
141 Bool -- True <=> might cause Haskell
142 -- garbage-collection (must generate
143 -- more paranoid code)
144 Bool -- True <=> it's really a "casm"
145 -- NOTE: this CCall is the *boxed*
146 -- version; the desugarer will convert
147 -- it into the unboxed "ccall#".
148 Type -- The result type; will be *bottom*
149 -- until the typechecker gets ahold of it
151 | HsSCC FAST_STRING -- "set cost centre" (_scc_) annotation
152 (HsExpr id pat) -- expr whose cost is to be measured
156 These constructors only appear temporarily in the parser.
157 The renamer translates them into the Right Thing.
160 | EWildPat -- wildcard
162 | EAsPat id -- as pattern
165 | ELazyPat (HsExpr id pat) -- ~ pattern
167 | HsType (HsType id) -- Explicit type argument; e.g f {| Int |} x y
170 Everything from here on appears only in typechecker output.
173 | TyLam -- TRANSLATION
176 | TyApp -- TRANSLATION
177 (HsExpr id pat) -- generated by Spec
180 -- DictLam and DictApp are "inverses"
188 type HsRecordBinds id pat
189 = [(id, HsExpr id pat, Bool)]
190 -- True <=> source code used "punning",
191 -- i.e. {op1, op2} rather than {op1=e1, op2=e2}
194 A @Dictionary@, unless of length 0 or 1, becomes a tuple. A
195 @ClassDictLam dictvars methods expr@ is, therefore:
197 \ x -> case x of ( dictvars-and-methods-tuple ) -> expr
201 instance (Outputable id, Outputable pat) =>
202 Outputable (HsExpr id pat) where
203 ppr expr = pprExpr expr
207 pprExpr :: (Outputable id, Outputable pat)
208 => HsExpr id pat -> SDoc
210 pprExpr e = pprDeeper (ppr_expr e)
211 pprBinds b = pprDeeper (ppr b)
214 -- Put it in parens if it's an operator
215 | isOperator v = parens (ppr v)
218 ppr_expr (HsIPVar v) = {- char '?' <> -} ppr v
219 ppr_expr (HsLit lit) = ppr lit
220 ppr_expr (HsOverLit lit) = ppr lit
222 ppr_expr (HsLam match)
223 = hsep [char '\\', nest 2 (pprMatch (True,empty) match)]
225 ppr_expr expr@(HsApp e1 e2)
226 = let (fun, args) = collect_args expr [] in
227 (ppr_expr fun) <+> (sep (map ppr_expr args))
229 collect_args (HsApp fun arg) args = collect_args fun (arg:args)
230 collect_args fun args = (fun, args)
232 ppr_expr (OpApp e1 op fixity e2)
234 HsVar v -> pp_infixly v
237 pp_e1 = pprParendExpr e1 -- Add parens to make precedence clear
238 pp_e2 = pprParendExpr e2
241 = hang (pprExpr op) 4 (sep [pp_e1, pp_e2])
244 = sep [pp_e1, hsep [pp_v_op, pp_e2]]
246 pp_v_op | isOperator v = ppr v
247 | otherwise = char '`' <> ppr v <> char '`'
248 -- Put it in backquotes if it's not an operator already
250 ppr_expr (NegApp e) = char '-' <+> pprParendExpr e
252 ppr_expr (HsPar e) = parens (ppr_expr e)
254 ppr_expr (SectionL expr op)
256 HsVar v -> pp_infixly v
259 pp_expr = pprParendExpr expr
261 pp_prefixly = hang (hsep [text " \\ x_ ->", ppr op])
262 4 (hsep [pp_expr, ptext SLIT("x_ )")])
263 pp_infixly v = parens (sep [pp_expr, ppr v])
265 ppr_expr (SectionR op expr)
267 HsVar v -> pp_infixly v
270 pp_expr = pprParendExpr expr
272 pp_prefixly = hang (hsep [text "( \\ x_ ->", ppr op, ptext SLIT("x_")])
273 4 ((<>) pp_expr rparen)
275 = parens (sep [ppr v, pp_expr])
277 ppr_expr (HsCase expr matches _)
278 = sep [ sep [ptext SLIT("case"), nest 4 (pprExpr expr), ptext SLIT("of")],
279 nest 2 (pprMatches (True, empty) matches) ]
281 ppr_expr (HsIf e1 e2 e3 _)
282 = sep [hsep [ptext SLIT("if"), nest 2 (pprExpr e1), ptext SLIT("then")],
287 -- special case: let ... in let ...
288 ppr_expr (HsLet binds expr@(HsLet _ _))
289 = sep [hang (ptext SLIT("let")) 2 (hsep [pprBinds binds, ptext SLIT("in")]),
292 ppr_expr (HsLet binds expr)
293 = sep [hang (ptext SLIT("let")) 2 (pprBinds binds),
294 hang (ptext SLIT("in")) 2 (ppr expr)]
296 ppr_expr (HsWith expr binds)
297 = hsep [ppr expr, ptext SLIT("with"), ppr binds]
299 ppr_expr (HsDo do_or_list_comp stmts _) = pprDo do_or_list_comp stmts
300 ppr_expr (HsDoOut do_or_list_comp stmts _ _ _ _ _) = pprDo do_or_list_comp stmts
302 ppr_expr (ExplicitList exprs)
303 = brackets (fsep (punctuate comma (map ppr_expr exprs)))
304 ppr_expr (ExplicitListOut ty exprs)
305 = brackets (fsep (punctuate comma (map ppr_expr exprs)))
307 ppr_expr (ExplicitTuple exprs boxity)
308 = tupleParens boxity (sep (punctuate comma (map ppr_expr exprs)))
310 ppr_expr (RecordCon con_id rbinds)
311 = pp_rbinds (ppr con_id) rbinds
312 ppr_expr (RecordConOut data_con con rbinds)
313 = pp_rbinds (ppr con) rbinds
315 ppr_expr (RecordUpd aexp rbinds)
316 = pp_rbinds (pprParendExpr aexp) rbinds
317 ppr_expr (RecordUpdOut aexp _ _ rbinds)
318 = pp_rbinds (pprParendExpr aexp) rbinds
320 ppr_expr (ExprWithTySig expr sig)
321 = hang (nest 2 (ppr_expr expr) <+> dcolon)
324 ppr_expr (ArithSeqIn info)
325 = brackets (ppr info)
326 ppr_expr (ArithSeqOut expr info)
327 = brackets (ppr info)
329 ppr_expr EWildPat = char '_'
330 ppr_expr (ELazyPat e) = char '~' <> pprParendExpr e
331 ppr_expr (EAsPat v e) = ppr v <> char '@' <> pprParendExpr e
333 ppr_expr (HsCCall fun args _ is_asm result_ty)
335 then ptext SLIT("_casm_ ``") <> pprCLabelString fun <> ptext SLIT("''")
336 else ptext SLIT("_ccall_") <+> pprCLabelString fun)
337 4 (sep (map pprParendExpr args))
339 ppr_expr (HsSCC lbl expr)
340 = sep [ ptext SLIT("_scc_") <+> doubleQuotes (ptext lbl), pprParendExpr expr ]
342 ppr_expr (TyLam tyvars expr)
343 = hang (hsep [ptext SLIT("/\\"), interppSP tyvars, ptext SLIT("->")])
346 ppr_expr (TyApp expr [ty])
347 = hang (ppr_expr expr) 4 (pprParendType ty)
349 ppr_expr (TyApp expr tys)
350 = hang (ppr_expr expr)
351 4 (brackets (interpp'SP tys))
353 ppr_expr (DictLam dictvars expr)
354 = hang (hsep [ptext SLIT("\\{-dict-}"), interppSP dictvars, ptext SLIT("->")])
357 ppr_expr (DictApp expr [dname])
358 = hang (ppr_expr expr) 4 (ppr dname)
360 ppr_expr (DictApp expr dnames)
361 = hang (ppr_expr expr)
362 4 (brackets (interpp'SP dnames))
364 ppr_expr (HsType id) = ppr id
368 Parenthesize unless very simple:
370 pprParendExpr :: (Outputable id, Outputable pat)
371 => HsExpr id pat -> SDoc
375 pp_as_was = pprExpr expr
382 HsIPVar _ -> pp_as_was
383 ExplicitList _ -> pp_as_was
384 ExplicitListOut _ _ -> pp_as_was
385 ExplicitTuple _ _ -> pp_as_was
388 _ -> parens pp_as_was
392 isOperator :: Outputable a => a -> Bool
393 isOperator v = isLexSym (_PK_ (showSDocUnqual (ppr v)))
394 -- We use (showSDoc (ppr v)), rather than isSymOcc (getOccName v) simply so
395 -- that we don't need NamedThing in the context of all these functions.
396 -- Gruesome, but simple.
399 %************************************************************************
401 \subsection{Record binds}
403 %************************************************************************
406 pp_rbinds :: (Outputable id, Outputable pat)
408 -> HsRecordBinds id pat -> SDoc
410 pp_rbinds thing rbinds
412 4 (braces (sep (punctuate comma (map (pp_rbind) rbinds))))
414 pp_rbind (v, e, pun_flag)
415 = getPprStyle $ \ sty ->
416 if pun_flag && userStyle sty then
419 hsep [ppr v, char '=', ppr e]
424 %************************************************************************
426 \subsection{@Match@, @GRHSs@, and @GRHS@ datatypes}
428 %************************************************************************
430 @Match@es are sets of pattern bindings and right hand sides for
431 functions, patterns or case branches. For example, if a function @g@
437 then \tr{g} has two @Match@es: @(x,y) = y@ and @((x:ys),y) = y+1@.
439 It is always the case that each element of an @[Match]@ list has the
440 same number of @pats@s inside it. This corresponds to saying that
441 a function defined by pattern matching must have the same number of
442 patterns in each equation.
447 [id] -- Tyvars wrt which this match is universally quantified
448 -- empty after typechecking
449 [pat] -- The patterns
450 (Maybe (HsType id)) -- A type signature for the result of the match
451 -- Nothing after typechecking
455 -- GRHSs are used both for pattern bindings and for Matches
457 = GRHSs [GRHS id pat] -- Guarded RHSs
458 (HsBinds id pat) -- The where clause
459 (Maybe Type) -- Just rhs_ty after type checking
462 = GRHS [Stmt id pat] -- The RHS is the final ExprStmt
463 -- I considered using a RetunStmt, but
464 -- it printed 'wrong' in error messages
467 mkSimpleMatch :: [pat] -> HsExpr id pat -> Maybe Type -> SrcLoc -> Match id pat
468 mkSimpleMatch pats rhs maybe_rhs_ty locn
469 = Match [] pats Nothing (GRHSs (unguardedRHS rhs locn) EmptyBinds maybe_rhs_ty)
471 unguardedRHS :: HsExpr id pat -> SrcLoc -> [GRHS id pat]
472 unguardedRHS rhs loc = [GRHS [ExprStmt rhs loc] loc]
475 @getMatchLoc@ takes a @Match@ and returns the
476 source-location gotten from the GRHS inside.
477 THis is something of a nuisance, but no more.
480 getMatchLoc :: Match id pat -> SrcLoc
481 getMatchLoc (Match _ _ _ (GRHSs (GRHS _ loc : _) _ _)) = loc
484 We know the list must have at least one @Match@ in it.
487 pprMatches :: (Outputable id, Outputable pat)
488 => (Bool, SDoc) -> [Match id pat] -> SDoc
489 pprMatches print_info matches = vcat (map (pprMatch print_info) matches)
492 pprMatch :: (Outputable id, Outputable pat)
493 => (Bool, SDoc) -> Match id pat -> SDoc
494 pprMatch print_info@(is_case, name) (Match _ pats maybe_ty grhss)
495 = maybe_name <+> sep [sep (map ppr pats),
497 nest 2 (pprGRHSs is_case grhss)]
499 maybe_name | is_case = empty
501 ppr_maybe_ty = case maybe_ty of
502 Just ty -> dcolon <+> ppr ty
506 pprGRHSs :: (Outputable id, Outputable pat)
507 => Bool -> GRHSs id pat -> SDoc
508 pprGRHSs is_case (GRHSs grhss binds maybe_ty)
509 = vcat (map (pprGRHS is_case) grhss)
511 (if nullBinds binds then empty
512 else text "where" $$ nest 4 (pprDeeper (ppr binds)))
515 pprGRHS :: (Outputable id, Outputable pat)
516 => Bool -> GRHS id pat -> SDoc
518 pprGRHS is_case (GRHS [ExprStmt expr _] locn)
519 = text (if is_case then "->" else "=") <+> pprDeeper (ppr expr)
521 pprGRHS is_case (GRHS guarded locn)
522 = sep [char '|' <+> interpp'SP guards,
523 text (if is_case then "->" else "=") <+> pprDeeper (ppr expr)
526 ExprStmt expr _ = last guarded -- Last stmt should be a ExprStmt for guards
527 guards = init guarded
532 %************************************************************************
534 \subsection{Do stmts and list comprehensions}
536 %************************************************************************
540 = BindStmt pat (HsExpr id pat) SrcLoc
541 | LetStmt (HsBinds id pat)
542 | ExprStmt (HsExpr id pat) SrcLoc -- See notes that follow
543 | ParStmt [[Stmt id pat]] -- List comp only: parallel set of quals
544 | ParStmtOut [([id], [Stmt id pat])] -- PLC after renaming
547 ExprStmts are a bit tricky, because what
548 they mean depends on the context. Consider
550 in the following contexts:
552 A do expression of type (m res_ty)
553 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
554 * Non-last stmt in list: do { ....; E; ... }
556 Translation: E >> ...
558 * Last stmt in list: do { ....; E }
562 A list comprehensions of type [elt_ty]
563 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
564 * Non-last stmt in list: [ .. | ..., E, ... ]
566 Translation: if E then fail else ...
568 * Last stmt in list: [ E | ... ]
570 Translation: return E
572 A guard list, guarding a RHS of type rhs_ty
573 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
574 * Non-last stmt in list: f x | ..., E, ... = ...rhs...
576 Translation: if E then fail else ...
578 * Last stmt in list: f x | ...guards... = E
583 consLetStmt :: HsBinds id pat -> [Stmt id pat] -> [Stmt id pat]
584 consLetStmt EmptyBinds stmts = stmts
585 consLetStmt binds stmts = LetStmt binds : stmts
589 instance (Outputable id, Outputable pat) =>
590 Outputable (Stmt id pat) where
591 ppr stmt = pprStmt stmt
593 pprStmt (ParStmt stmtss)
594 = hsep (map (\stmts -> ptext SLIT("| ") <> ppr stmts) stmtss)
595 pprStmt (ParStmtOut stmtss)
596 = hsep (map (\stmts -> ptext SLIT("| ") <> ppr stmts) stmtss)
597 pprStmt (BindStmt pat expr _)
598 = hsep [ppr pat, ptext SLIT("<-"), ppr expr]
599 pprStmt (LetStmt binds)
600 = hsep [ptext SLIT("let"), pprBinds binds]
601 pprStmt (ExprStmt expr _)
604 pprDo :: (Outputable id, Outputable pat) => HsMatchContext -> [Stmt id pat] -> SDoc
605 pprDo DoExpr stmts = hang (ptext SLIT("do")) 2 (vcat (map ppr stmts))
606 pprDo ListComp stmts = brackets $
607 hang (pprExpr expr <+> char '|')
610 ExprStmt expr _ = last stmts -- Last stmt should
611 quals = init stmts -- be an ExprStmt
614 %************************************************************************
616 \subsection{Enumerations and list comprehensions}
618 %************************************************************************
621 data ArithSeqInfo id pat
622 = From (HsExpr id pat)
623 | FromThen (HsExpr id pat)
625 | FromTo (HsExpr id pat)
627 | FromThenTo (HsExpr id pat)
633 instance (Outputable id, Outputable pat) =>
634 Outputable (ArithSeqInfo id pat) where
635 ppr (From e1) = hcat [ppr e1, pp_dotdot]
636 ppr (FromThen e1 e2) = hcat [ppr e1, comma, space, ppr e2, pp_dotdot]
637 ppr (FromTo e1 e3) = hcat [ppr e1, pp_dotdot, ppr e3]
638 ppr (FromThenTo e1 e2 e3)
639 = hcat [ppr e1, comma, space, ppr e2, pp_dotdot, ppr e3]
641 pp_dotdot = ptext SLIT(" .. ")
645 %************************************************************************
647 \subsection{HsMatchCtxt}
649 %************************************************************************
652 data HsMatchContext -- Context of a Match or Stmt
653 = ListComp -- List comprehension
654 | DoExpr -- Do Statment
656 | FunRhs Name -- Function binding for f
657 | CaseAlt -- Guard on a case alternative
658 | LambdaExpr -- Lambda
659 | PatBindRhs -- Pattern binding
660 | RecUpd -- Record update
663 -- It's convenient to have FunRhs as a Name
664 -- throughout so that HsMatchContext doesn't
665 -- need to be parameterised.
666 -- In the RdrName world we never use the FunRhs variant.
670 isDoExpr DoExpr = True
671 isDoExpr other = False
673 isDoOrListComp ListComp = True
674 isDoOrListComp DoExpr = True
675 isDoOrListComp other = False
679 matchSeparator (FunRhs _) = SLIT("=")
680 matchSeparator CaseAlt = SLIT("->")
681 matchSeparator LambdaExpr = SLIT("->")
682 matchSeparator PatBindRhs = SLIT("=")
683 matchSeparator DoExpr = SLIT("<-")
684 matchSeparator ListComp = SLIT("<-")
685 matchSeparator RecUpd = panic "When is this used?"
689 pprMatchContext (FunRhs fun) = ptext SLIT("in the definition of function") <+> quotes (ppr fun)
690 pprMatchContext CaseAlt = ptext SLIT("in a group of case alternatives beginning")
691 pprMatchContext RecUpd = ptext SLIT("in a record-update construct")
692 pprMatchContext PatBindRhs = ptext SLIT("in a pattern binding")
693 pprMatchContext LambdaExpr = ptext SLIT("in a lambda abstraction")
694 pprMatchContext DoExpr = ptext SLIT("in a `do' expression pattern binding")
695 pprMatchContext ListComp = ptext SLIT("in a `list comprension' pattern binding")