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 )
19 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
100 | ExplicitListOut -- TRANSLATION
101 Type -- Gives type of components of list
104 | ExplicitTuple -- tuple
106 -- NB: Unit is ExplicitTuple []
107 -- for tuples, we can get the types
108 -- direct from the components
112 -- Record construction
113 | RecordCon id -- The constructor
114 (HsRecordBinds id pat)
116 | RecordConOut DataCon
117 (HsExpr id pat) -- Data con Id applied to type args
118 (HsRecordBinds id pat)
122 | RecordUpd (HsExpr id pat)
123 (HsRecordBinds id pat)
125 | RecordUpdOut (HsExpr id pat) -- TRANSLATION
126 Type -- Type of *result* record (may differ from
127 -- type of input record)
128 [id] -- Dicts needed for construction
129 (HsRecordBinds id pat)
131 | ExprWithTySig -- signature binding
134 | ArithSeqIn -- arithmetic sequence
135 (ArithSeqInfo id pat)
137 (HsExpr id pat) -- (typechecked, of course)
138 (ArithSeqInfo id pat)
140 | HsCCall CLabelString -- call into the C world; string is
141 [HsExpr id pat] -- the C function; exprs are the
142 -- arguments to pass.
143 Safety -- True <=> might cause Haskell
144 -- garbage-collection (must generate
145 -- more paranoid code)
146 Bool -- True <=> it's really a "casm"
147 -- NOTE: this CCall is the *boxed*
148 -- version; the desugarer will convert
149 -- it into the unboxed "ccall#".
150 Type -- The result type; will be *bottom*
151 -- until the typechecker gets ahold of it
153 | HsSCC FAST_STRING -- "set cost centre" (_scc_) annotation
154 (HsExpr id pat) -- expr whose cost is to be measured
158 These constructors only appear temporarily in the parser.
159 The renamer translates them into the Right Thing.
162 | EWildPat -- wildcard
164 | EAsPat id -- as pattern
167 | ELazyPat (HsExpr id pat) -- ~ pattern
169 | HsType (HsType id) -- Explicit type argument; e.g f {| Int |} x y
172 Everything from here on appears only in typechecker output.
175 | TyLam -- TRANSLATION
178 | TyApp -- TRANSLATION
179 (HsExpr id pat) -- generated by Spec
182 -- DictLam and DictApp are "inverses"
190 type HsRecordBinds id pat
191 = [(id, HsExpr id pat, Bool)]
192 -- True <=> source code used "punning",
193 -- i.e. {op1, op2} rather than {op1=e1, op2=e2}
196 A @Dictionary@, unless of length 0 or 1, becomes a tuple. A
197 @ClassDictLam dictvars methods expr@ is, therefore:
199 \ x -> case x of ( dictvars-and-methods-tuple ) -> expr
203 instance (Outputable id, Outputable pat) =>
204 Outputable (HsExpr id pat) where
205 ppr expr = pprExpr expr
209 pprExpr :: (Outputable id, Outputable pat)
210 => HsExpr id pat -> SDoc
212 pprExpr e = pprDeeper (ppr_expr e)
213 pprBinds b = pprDeeper (ppr b)
216 -- Put it in parens if it's an operator
217 | isOperator v = parens (ppr v)
220 ppr_expr (HsIPVar v) = char '?' <> ppr v
221 ppr_expr (HsLit lit) = ppr lit
222 ppr_expr (HsOverLit lit) = ppr lit
224 ppr_expr (HsLam match)
225 = hsep [char '\\', nest 2 (pprMatch LambdaExpr match)]
227 ppr_expr expr@(HsApp e1 e2)
228 = let (fun, args) = collect_args expr [] in
229 (ppr_expr fun) <+> (sep (map ppr_expr args))
231 collect_args (HsApp fun arg) args = collect_args fun (arg:args)
232 collect_args fun args = (fun, args)
234 ppr_expr (OpApp e1 op fixity e2)
236 HsVar v -> pp_infixly v
239 pp_e1 = pprParendExpr e1 -- Add parens to make precedence clear
240 pp_e2 = pprParendExpr e2
243 = hang (pprExpr op) 4 (sep [pp_e1, pp_e2])
246 = sep [pp_e1, hsep [pp_v_op, pp_e2]]
248 pp_v_op | isOperator v = ppr v
249 | otherwise = char '`' <> ppr v <> char '`'
250 -- Put it in backquotes if it's not an operator already
252 ppr_expr (NegApp e) = char '-' <+> pprParendExpr e
254 ppr_expr (HsPar e) = parens (ppr_expr e)
256 ppr_expr (SectionL expr op)
258 HsVar v -> pp_infixly v
261 pp_expr = pprParendExpr expr
263 pp_prefixly = hang (hsep [text " \\ x_ ->", ppr op])
264 4 (hsep [pp_expr, ptext SLIT("x_ )")])
265 pp_infixly v = parens (sep [pp_expr, ppr v])
267 ppr_expr (SectionR op expr)
269 HsVar v -> pp_infixly v
272 pp_expr = pprParendExpr expr
274 pp_prefixly = hang (hsep [text "( \\ x_ ->", ppr op, ptext SLIT("x_")])
275 4 ((<>) pp_expr rparen)
277 = parens (sep [ppr v, pp_expr])
279 ppr_expr (HsCase expr matches _)
280 = sep [ sep [ptext SLIT("case"), nest 4 (pprExpr expr), ptext SLIT("of")],
281 nest 2 (pprMatches CaseAlt matches) ]
283 ppr_expr (HsIf e1 e2 e3 _)
284 = sep [hsep [ptext SLIT("if"), nest 2 (pprExpr e1), ptext SLIT("then")],
289 -- special case: let ... in let ...
290 ppr_expr (HsLet binds expr@(HsLet _ _))
291 = sep [hang (ptext SLIT("let")) 2 (hsep [pprBinds binds, ptext SLIT("in")]),
294 ppr_expr (HsLet binds expr)
295 = sep [hang (ptext SLIT("let")) 2 (pprBinds binds),
296 hang (ptext SLIT("in")) 2 (ppr expr)]
298 ppr_expr (HsWith expr binds)
299 = hsep [ppr expr, ptext SLIT("with"), ppr binds]
301 ppr_expr (HsDo do_or_list_comp stmts _) = pprDo do_or_list_comp stmts
302 ppr_expr (HsDoOut do_or_list_comp stmts _ _ _ _ _) = pprDo do_or_list_comp stmts
304 ppr_expr (ExplicitList exprs)
305 = brackets (fsep (punctuate comma (map ppr_expr exprs)))
306 ppr_expr (ExplicitListOut ty exprs)
307 = brackets (fsep (punctuate comma (map ppr_expr exprs)))
309 ppr_expr (ExplicitTuple exprs boxity)
310 = tupleParens boxity (sep (punctuate comma (map ppr_expr exprs)))
312 ppr_expr (RecordCon con_id rbinds)
313 = pp_rbinds (ppr con_id) rbinds
314 ppr_expr (RecordConOut data_con con rbinds)
315 = pp_rbinds (ppr con) rbinds
317 ppr_expr (RecordUpd aexp rbinds)
318 = pp_rbinds (pprParendExpr aexp) rbinds
319 ppr_expr (RecordUpdOut aexp _ _ rbinds)
320 = pp_rbinds (pprParendExpr aexp) rbinds
322 ppr_expr (ExprWithTySig expr sig)
323 = hang (nest 2 (ppr_expr expr) <+> dcolon)
326 ppr_expr (ArithSeqIn info)
327 = brackets (ppr info)
328 ppr_expr (ArithSeqOut expr info)
329 = brackets (ppr info)
331 ppr_expr EWildPat = char '_'
332 ppr_expr (ELazyPat e) = char '~' <> pprParendExpr e
333 ppr_expr (EAsPat v e) = ppr v <> char '@' <> pprParendExpr e
335 ppr_expr (HsCCall fun args _ is_asm result_ty)
337 then ptext SLIT("_casm_ ``") <> pprCLabelString fun <> ptext SLIT("''")
338 else ptext SLIT("_ccall_") <+> pprCLabelString fun)
339 4 (sep (map pprParendExpr args))
341 ppr_expr (HsSCC lbl expr)
342 = sep [ ptext SLIT("_scc_") <+> doubleQuotes (ptext lbl), pprParendExpr expr ]
344 ppr_expr (TyLam tyvars expr)
345 = hang (hsep [ptext SLIT("/\\"), interppSP tyvars, ptext SLIT("->")])
348 ppr_expr (TyApp expr [ty])
349 = hang (ppr_expr expr) 4 (pprParendType ty)
351 ppr_expr (TyApp expr tys)
352 = hang (ppr_expr expr)
353 4 (brackets (interpp'SP tys))
355 ppr_expr (DictLam dictvars expr)
356 = hang (hsep [ptext SLIT("\\{-dict-}"), interppSP dictvars, ptext SLIT("->")])
359 ppr_expr (DictApp expr [dname])
360 = hang (ppr_expr expr) 4 (ppr dname)
362 ppr_expr (DictApp expr dnames)
363 = hang (ppr_expr expr)
364 4 (brackets (interpp'SP dnames))
366 ppr_expr (HsType id) = ppr id
370 Parenthesize unless very simple:
372 pprParendExpr :: (Outputable id, Outputable pat)
373 => HsExpr id pat -> SDoc
377 pp_as_was = pprExpr expr
384 HsIPVar _ -> pp_as_was
385 ExplicitList _ -> pp_as_was
386 ExplicitListOut _ _ -> pp_as_was
387 ExplicitTuple _ _ -> pp_as_was
390 _ -> parens pp_as_was
393 %************************************************************************
395 \subsection{Record binds}
397 %************************************************************************
400 pp_rbinds :: (Outputable id, Outputable pat)
402 -> HsRecordBinds id pat -> SDoc
404 pp_rbinds thing rbinds
406 4 (braces (sep (punctuate comma (map (pp_rbind) rbinds))))
408 pp_rbind (v, e, pun_flag)
409 = getPprStyle $ \ sty ->
410 if pun_flag && userStyle sty then
413 hsep [ppr v, char '=', ppr e]
418 %************************************************************************
420 \subsection{@Match@, @GRHSs@, and @GRHS@ datatypes}
422 %************************************************************************
424 @Match@es are sets of pattern bindings and right hand sides for
425 functions, patterns or case branches. For example, if a function @g@
431 then \tr{g} has two @Match@es: @(x,y) = y@ and @((x:ys),y) = y+1@.
433 It is always the case that each element of an @[Match]@ list has the
434 same number of @pats@s inside it. This corresponds to saying that
435 a function defined by pattern matching must have the same number of
436 patterns in each equation.
441 [id] -- Tyvars wrt which this match is universally quantified
442 -- empty after typechecking
443 [pat] -- The patterns
444 (Maybe (HsType id)) -- A type signature for the result of the match
445 -- Nothing after typechecking
449 -- GRHSs are used both for pattern bindings and for Matches
451 = GRHSs [GRHS id pat] -- Guarded RHSs
452 (HsBinds id pat) -- The where clause
453 (Maybe Type) -- Just rhs_ty after type checking
456 = GRHS [Stmt id pat] -- The RHS is the final ResultStmt
457 -- I considered using a RetunStmt, but
458 -- it printed 'wrong' in error messages
461 mkSimpleMatch :: [pat] -> HsExpr id pat -> Maybe Type -> SrcLoc -> Match id pat
462 mkSimpleMatch pats rhs maybe_rhs_ty locn
463 = Match [] pats Nothing (GRHSs (unguardedRHS rhs locn) EmptyBinds maybe_rhs_ty)
465 unguardedRHS :: HsExpr id pat -> SrcLoc -> [GRHS id pat]
466 unguardedRHS rhs loc = [GRHS [ResultStmt rhs loc] loc]
469 @getMatchLoc@ takes a @Match@ and returns the
470 source-location gotten from the GRHS inside.
471 THis is something of a nuisance, but no more.
474 getMatchLoc :: Match id pat -> SrcLoc
475 getMatchLoc (Match _ _ _ (GRHSs (GRHS _ loc : _) _ _)) = loc
478 We know the list must have at least one @Match@ in it.
481 pprMatches :: (Outputable id, Outputable pat)
482 => HsMatchContext id -> [Match id pat] -> SDoc
483 pprMatches ctxt matches = vcat (map (pprMatch ctxt) matches)
485 -- Exported to HsBinds, which can't see the defn of HsMatchContext
486 pprFunBind :: (Outputable id, Outputable pat)
487 => id -> [Match id pat] -> SDoc
488 pprFunBind fun matches = pprMatches (FunRhs fun) matches
490 -- Exported to HsBinds, which can't see the defn of HsMatchContext
491 pprPatBind :: (Outputable id, Outputable pat)
492 => pat -> GRHSs id pat -> SDoc
493 pprPatBind pat grhss = sep [ppr pat, nest 4 (pprGRHSs PatBindRhs grhss)]
496 pprMatch :: (Outputable id, Outputable pat)
497 => HsMatchContext id -> Match id pat -> SDoc
498 pprMatch ctxt (Match _ pats maybe_ty grhss)
499 = pp_name ctxt <+> sep [sep (map ppr pats),
501 nest 2 (pprGRHSs ctxt grhss)]
503 pp_name (FunRhs fun) = ppr fun
504 pp_name other = empty
505 ppr_maybe_ty = case maybe_ty of
506 Just ty -> dcolon <+> ppr ty
510 pprGRHSs :: (Outputable id, Outputable pat)
511 => HsMatchContext id -> GRHSs id pat -> SDoc
512 pprGRHSs ctxt (GRHSs grhss binds maybe_ty)
513 = vcat (map (pprGRHS ctxt) grhss)
515 (if nullBinds binds then empty
516 else text "where" $$ nest 4 (pprDeeper (ppr binds)))
519 pprGRHS :: (Outputable id, Outputable pat)
520 => HsMatchContext id -> GRHS id pat -> SDoc
522 pprGRHS ctxt (GRHS [ResultStmt expr _] locn)
525 pprGRHS ctxt (GRHS guarded locn)
526 = sep [char '|' <+> interpp'SP guards, pp_rhs ctxt expr]
528 ResultStmt expr _ = last guarded -- Last stmt should be a ResultStmt for guards
529 guards = init guarded
531 pp_rhs ctxt rhs = ptext (matchSeparator ctxt) <+> pprDeeper (ppr rhs)
536 %************************************************************************
538 \subsection{Do stmts and list comprehensions}
540 %************************************************************************
544 = BindStmt pat (HsExpr id pat) SrcLoc
545 | LetStmt (HsBinds id pat)
546 | ResultStmt (HsExpr id pat) SrcLoc -- See notes that follow
547 | ExprStmt (HsExpr id pat) SrcLoc -- See notes that follow
548 | ParStmt [[Stmt id pat]] -- List comp only: parallel set of quals
549 | ParStmtOut [([id], [Stmt id pat])] -- PLC after renaming; the ids are the binders
550 -- bound by the stmts
553 ExprStmts and ResultStmts are a bit tricky, because what they mean
554 depends on the context. Consider the following contexts:
556 A do expression of type (m res_ty)
557 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
558 * ExprStmt E: do { ....; E; ... }
560 Translation: E >> ...
562 * ResultStmt E: do { ....; E }
566 A list comprehensions of type [elt_ty]
567 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
568 * ExprStmt E: [ .. | .... E ]
570 [ .. | .... | ..., E | ... ]
572 Translation: if E then fail else ...
574 * ResultStmt E: [ E | ... ]
576 Translation: return E
578 A guard list, guarding a RHS of type rhs_ty
579 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
580 * ExprStmt E: f x | ..., E, ... = ...rhs...
582 Translation: if E then fail else ...
584 * ResultStmt E: f x | ...guards... = E
590 consLetStmt :: HsBinds id pat -> [Stmt id pat] -> [Stmt id pat]
591 consLetStmt EmptyBinds stmts = stmts
592 consLetStmt binds stmts = LetStmt binds : stmts
596 instance (Outputable id, Outputable pat) =>
597 Outputable (Stmt id pat) where
598 ppr stmt = pprStmt stmt
600 pprStmt (BindStmt pat expr _) = hsep [ppr pat, ptext SLIT("<-"), ppr expr]
601 pprStmt (LetStmt binds) = hsep [ptext SLIT("let"), pprBinds binds]
602 pprStmt (ExprStmt expr _) = ppr expr
603 pprStmt (ResultStmt expr _) = ppr expr
604 pprStmt (ParStmt stmtss)
605 = hsep (map (\stmts -> ptext SLIT("| ") <> ppr stmts) stmtss)
606 pprStmt (ParStmtOut stmtss)
607 = hsep (map (\stmts -> ptext SLIT("| ") <> ppr stmts) stmtss)
609 pprDo :: (Outputable id, Outputable pat) => HsDoContext -> [Stmt id pat] -> SDoc
610 pprDo DoExpr stmts = hang (ptext SLIT("do")) 2 (vcat (map ppr stmts))
611 pprDo ListComp stmts = brackets $
612 hang (pprExpr expr <+> char '|')
615 ResultStmt expr _ = last stmts -- Last stmt should
616 quals = init stmts -- be an ResultStmt
619 %************************************************************************
621 \subsection{Enumerations and list comprehensions}
623 %************************************************************************
626 data ArithSeqInfo id pat
627 = From (HsExpr id pat)
628 | FromThen (HsExpr id pat)
630 | FromTo (HsExpr id pat)
632 | FromThenTo (HsExpr id pat)
638 instance (Outputable id, Outputable pat) =>
639 Outputable (ArithSeqInfo id pat) where
640 ppr (From e1) = hcat [ppr e1, pp_dotdot]
641 ppr (FromThen e1 e2) = hcat [ppr e1, comma, space, ppr e2, pp_dotdot]
642 ppr (FromTo e1 e3) = hcat [ppr e1, pp_dotdot, ppr e3]
643 ppr (FromThenTo e1 e2 e3)
644 = hcat [ppr e1, comma, space, ppr e2, pp_dotdot, ppr e3]
646 pp_dotdot = ptext SLIT(" .. ")
650 %************************************************************************
652 \subsection{HsMatchCtxt}
654 %************************************************************************
657 data HsMatchContext id -- Context of a Match or Stmt
658 = DoCtxt HsDoContext -- Do-stmt or list comprehension
659 | FunRhs id -- Function binding for f
660 | CaseAlt -- Guard on a case alternative
661 | LambdaExpr -- Lambda
662 | PatBindRhs -- Pattern binding
663 | RecUpd -- Record update
666 data HsDoContext = ListComp | DoExpr
670 isDoExpr (DoCtxt DoExpr) = True
671 isDoExpr other = False
675 matchSeparator (FunRhs _) = SLIT("=")
676 matchSeparator CaseAlt = SLIT("->")
677 matchSeparator LambdaExpr = SLIT("->")
678 matchSeparator PatBindRhs = SLIT("=")
679 matchSeparator (DoCtxt _) = SLIT("<-")
680 matchSeparator RecUpd = panic "When is this used?"
684 pprMatchContext (FunRhs fun) = ptext SLIT("In the definition of") <+> quotes (ppr fun)
685 pprMatchContext CaseAlt = ptext SLIT("In a case alternative")
686 pprMatchContext RecUpd = ptext SLIT("In a record-update construct")
687 pprMatchContext PatBindRhs = ptext SLIT("In a pattern binding")
688 pprMatchContext LambdaExpr = ptext SLIT("In a lambda abstraction")
689 pprMatchContext (DoCtxt DoExpr) = ptext SLIT("In a 'do' expression pattern binding")
690 pprMatchContext (DoCtxt ListComp) = ptext SLIT("In a 'list comprehension' pattern binding")
692 -- Used to generate the string for a *runtime* error message
693 matchContextErrString (FunRhs fun) = "function " ++ showSDoc (ppr fun)
694 matchContextErrString CaseAlt = "case"
695 matchContextErrString PatBindRhs = "pattern binding"
696 matchContextErrString RecUpd = "record update"
697 matchContextErrString LambdaExpr = "lambda"
698 matchContextErrString (DoCtxt DoExpr) = "'do' expression"
699 matchContextErrString (DoCtxt ListComp) = "list comprehension"