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 ( Boxity, tupleParens )
29 import SrcLoc ( SrcLoc )
32 %************************************************************************
34 \subsection{Expressions proper}
36 %************************************************************************
40 = HsVar id -- variable
41 | HsIPVar 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
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 | 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 *input* record
127 Type -- Type of *result* record (may differ from
128 -- type of input record)
129 [id] -- Dicts needed for construction
130 (HsRecordBinds id pat)
132 | ExprWithTySig -- signature binding
135 | ArithSeqIn -- arithmetic sequence
136 (ArithSeqInfo id pat)
138 (HsExpr id pat) -- (typechecked, of course)
139 (ArithSeqInfo id pat)
141 | HsCCall CLabelString -- call into the C world; string is
142 [HsExpr id pat] -- the C function; exprs are the
143 -- arguments to pass.
144 Safety -- True <=> might cause Haskell
145 -- garbage-collection (must generate
146 -- more paranoid code)
147 Bool -- True <=> it's really a "casm"
148 -- NOTE: this CCall is the *boxed*
149 -- version; the desugarer will convert
150 -- it into the unboxed "ccall#".
151 PostTcType -- The result type; will be *bottom*
152 -- until the typechecker gets ahold of it
154 | HsSCC FAST_STRING -- "set cost centre" (_scc_) annotation
155 (HsExpr id pat) -- expr whose cost is to be measured
159 These constructors only appear temporarily in the parser.
160 The renamer translates them into the Right Thing.
163 | EWildPat -- wildcard
165 | EAsPat id -- as pattern
168 | ELazyPat (HsExpr id pat) -- ~ pattern
170 | HsType (HsType id) -- Explicit type argument; e.g f {| Int |} x y
173 Everything from here on appears only in typechecker output.
176 | TyLam -- TRANSLATION
179 | TyApp -- TRANSLATION
180 (HsExpr id pat) -- generated by Spec
183 -- DictLam and DictApp are "inverses"
191 type HsRecordBinds id pat
192 = [(id, HsExpr id pat, Bool)]
193 -- True <=> source code used "punning",
194 -- i.e. {op1, op2} rather than {op1=e1, op2=e2}
197 A @Dictionary@, unless of length 0 or 1, becomes a tuple. A
198 @ClassDictLam dictvars methods expr@ is, therefore:
200 \ x -> case x of ( dictvars-and-methods-tuple ) -> expr
204 instance (Outputable id, Outputable pat) =>
205 Outputable (HsExpr id pat) where
206 ppr expr = pprExpr expr
210 pprExpr :: (Outputable id, Outputable pat)
211 => HsExpr id pat -> SDoc
213 pprExpr e = pprDeeper (ppr_expr e)
214 pprBinds b = pprDeeper (ppr b)
217 -- Put it in parens if it's an operator
218 | isOperator v = parens (ppr v)
221 ppr_expr (HsIPVar v) = char '?' <> ppr v
222 ppr_expr (HsLit lit) = ppr lit
223 ppr_expr (HsOverLit lit) = ppr lit
225 ppr_expr (HsLam match)
226 = hsep [char '\\', nest 2 (pprMatch LambdaExpr match)]
228 ppr_expr expr@(HsApp e1 e2)
229 = let (fun, args) = collect_args expr [] in
230 (ppr_expr fun) <+> (sep (map ppr_expr args))
232 collect_args (HsApp fun arg) args = collect_args fun (arg:args)
233 collect_args fun args = (fun, args)
235 ppr_expr (OpApp e1 op fixity e2)
237 HsVar v -> pp_infixly v
240 pp_e1 = pprParendExpr e1 -- Add parens to make precedence clear
241 pp_e2 = pprParendExpr e2
244 = hang (pprExpr op) 4 (sep [pp_e1, pp_e2])
247 = sep [pp_e1, hsep [pp_v_op, pp_e2]]
249 pp_v_op | isOperator v = ppr v
250 | otherwise = char '`' <> ppr v <> char '`'
251 -- Put it in backquotes if it's not an operator already
253 ppr_expr (NegApp e _) = char '-' <+> pprParendExpr e
255 ppr_expr (HsPar e) = parens (ppr_expr e)
257 ppr_expr (SectionL expr op)
259 HsVar v -> pp_infixly v
262 pp_expr = pprParendExpr expr
264 pp_prefixly = hang (hsep [text " \\ x_ ->", ppr op])
265 4 (hsep [pp_expr, ptext SLIT("x_ )")])
266 pp_infixly v = parens (sep [pp_expr, ppr v])
268 ppr_expr (SectionR op expr)
270 HsVar v -> pp_infixly v
273 pp_expr = pprParendExpr expr
275 pp_prefixly = hang (hsep [text "( \\ x_ ->", ppr op, ptext SLIT("x_")])
276 4 ((<>) pp_expr rparen)
278 = parens (sep [ppr v, pp_expr])
280 ppr_expr (HsCase expr matches _)
281 = sep [ sep [ptext SLIT("case"), nest 4 (pprExpr expr), ptext SLIT("of")],
282 nest 2 (pprMatches CaseAlt matches) ]
284 ppr_expr (HsIf e1 e2 e3 _)
285 = sep [hsep [ptext SLIT("if"), nest 2 (pprExpr e1), ptext SLIT("then")],
290 -- special case: let ... in let ...
291 ppr_expr (HsLet binds expr@(HsLet _ _))
292 = sep [hang (ptext SLIT("let")) 2 (hsep [pprBinds binds, ptext SLIT("in")]),
295 ppr_expr (HsLet binds expr)
296 = sep [hang (ptext SLIT("let")) 2 (pprBinds binds),
297 hang (ptext SLIT("in")) 2 (ppr expr)]
299 ppr_expr (HsWith expr binds)
300 = hsep [ppr expr, ptext SLIT("with"), ppr binds]
302 ppr_expr (HsDo do_or_list_comp stmts _) = pprDo do_or_list_comp stmts
303 ppr_expr (HsDoOut do_or_list_comp stmts _ _ _ _ _) = pprDo do_or_list_comp stmts
305 ppr_expr (ExplicitList _ 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 ExplicitTuple _ _ -> pp_as_was
388 _ -> parens pp_as_was
391 %************************************************************************
393 \subsection{Record binds}
395 %************************************************************************
398 pp_rbinds :: (Outputable id, Outputable pat)
400 -> HsRecordBinds id pat -> SDoc
402 pp_rbinds thing rbinds
404 4 (braces (sep (punctuate comma (map (pp_rbind) rbinds))))
406 pp_rbind (v, e, pun_flag)
407 = getPprStyle $ \ sty ->
408 if pun_flag && userStyle sty then
411 hsep [ppr v, char '=', ppr e]
416 %************************************************************************
418 \subsection{@Match@, @GRHSs@, and @GRHS@ datatypes}
420 %************************************************************************
422 @Match@es are sets of pattern bindings and right hand sides for
423 functions, patterns or case branches. For example, if a function @g@
429 then \tr{g} has two @Match@es: @(x,y) = y@ and @((x:ys),y) = y+1@.
431 It is always the case that each element of an @[Match]@ list has the
432 same number of @pats@s inside it. This corresponds to saying that
433 a function defined by pattern matching must have the same number of
434 patterns in each equation.
439 [id] -- Tyvars wrt which this match is universally quantified
440 -- empty after typechecking
441 [pat] -- The patterns
442 (Maybe (HsType id)) -- A type signature for the result of the match
443 -- Nothing after typechecking
447 -- GRHSs are used both for pattern bindings and for Matches
449 = GRHSs [GRHS id pat] -- Guarded RHSs
450 (HsBinds id pat) -- The where clause
451 PostTcType -- Type of RHS (after type checking)
454 = GRHS [Stmt id pat] -- The RHS is the final ResultStmt
455 -- I considered using a RetunStmt, but
456 -- it printed 'wrong' in error messages
459 mkSimpleMatch :: [pat] -> HsExpr id pat -> Type -> SrcLoc -> Match id pat
460 mkSimpleMatch pats rhs rhs_ty locn
461 = Match [] pats Nothing (GRHSs (unguardedRHS rhs locn) EmptyBinds rhs_ty)
463 unguardedRHS :: HsExpr id pat -> SrcLoc -> [GRHS id pat]
464 unguardedRHS rhs loc = [GRHS [ResultStmt rhs loc] loc]
467 @getMatchLoc@ takes a @Match@ and returns the
468 source-location gotten from the GRHS inside.
469 THis is something of a nuisance, but no more.
472 getMatchLoc :: Match id pat -> SrcLoc
473 getMatchLoc (Match _ _ _ (GRHSs (GRHS _ loc : _) _ _)) = loc
476 We know the list must have at least one @Match@ in it.
479 pprMatches :: (Outputable id, Outputable pat)
480 => HsMatchContext id -> [Match id pat] -> SDoc
481 pprMatches ctxt matches = vcat (map (pprMatch ctxt) matches)
483 -- Exported to HsBinds, which can't see the defn of HsMatchContext
484 pprFunBind :: (Outputable id, Outputable pat)
485 => id -> [Match id pat] -> SDoc
486 pprFunBind fun matches = pprMatches (FunRhs fun) matches
488 -- Exported to HsBinds, which can't see the defn of HsMatchContext
489 pprPatBind :: (Outputable id, Outputable pat)
490 => pat -> GRHSs id pat -> SDoc
491 pprPatBind pat grhss = sep [ppr pat, nest 4 (pprGRHSs PatBindRhs grhss)]
494 pprMatch :: (Outputable id, Outputable pat)
495 => HsMatchContext id -> Match id pat -> SDoc
496 pprMatch ctxt (Match _ pats maybe_ty grhss)
497 = pp_name ctxt <+> sep [sep (map ppr pats),
499 nest 2 (pprGRHSs ctxt grhss)]
501 pp_name (FunRhs fun) = ppr fun
502 pp_name other = empty
503 ppr_maybe_ty = case maybe_ty of
504 Just ty -> dcolon <+> ppr ty
508 pprGRHSs :: (Outputable id, Outputable pat)
509 => HsMatchContext id -> GRHSs id pat -> SDoc
510 pprGRHSs ctxt (GRHSs grhss binds ty)
511 = vcat (map (pprGRHS ctxt) grhss)
513 (if nullBinds binds then empty
514 else text "where" $$ nest 4 (pprDeeper (ppr binds)))
517 pprGRHS :: (Outputable id, Outputable pat)
518 => HsMatchContext id -> GRHS id pat -> SDoc
520 pprGRHS ctxt (GRHS [ResultStmt expr _] locn)
523 pprGRHS ctxt (GRHS guarded locn)
524 = sep [char '|' <+> interpp'SP guards, pp_rhs ctxt expr]
526 ResultStmt expr _ = last guarded -- Last stmt should be a ResultStmt for guards
527 guards = init guarded
529 pp_rhs ctxt rhs = ptext (matchSeparator ctxt) <+> pprDeeper (ppr rhs)
534 %************************************************************************
536 \subsection{Do stmts and list comprehensions}
538 %************************************************************************
542 = BindStmt pat (HsExpr id pat) SrcLoc
543 | LetStmt (HsBinds id pat)
544 | ResultStmt (HsExpr id pat) SrcLoc -- See notes that follow
545 | ExprStmt (HsExpr id pat) PostTcType SrcLoc -- See notes that follow
546 -- The type is the *element type* of the expression
547 | ParStmt [[Stmt id pat]] -- List comp only: parallel set of quals
548 | ParStmtOut [([id], [Stmt id pat])] -- PLC after renaming; the ids are the binders
549 -- bound by the stmts
552 ExprStmts and ResultStmts are a bit tricky, because what they mean
553 depends on the context. Consider the following contexts:
555 A do expression of type (m res_ty)
556 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
557 * ExprStmt E any_ty: do { ....; E; ... }
559 Translation: E >> ...
561 * ResultStmt E: do { ....; E }
565 A list comprehensions of type [elt_ty]
566 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
567 * ExprStmt E Bool: [ .. | .... E ]
569 [ .. | .... | ..., E | ... ]
571 Translation: if E then fail else ...
573 * ResultStmt E: [ E | ... ]
575 Translation: return E
577 A guard list, guarding a RHS of type rhs_ty
578 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
579 * ExprStmt E Bool: f x | ..., E, ... = ...rhs...
581 Translation: if E then fail else ...
583 * ResultStmt E: f x | ...guards... = E
589 consLetStmt :: HsBinds id pat -> [Stmt id pat] -> [Stmt id pat]
590 consLetStmt EmptyBinds stmts = stmts
591 consLetStmt binds stmts = LetStmt binds : stmts
595 instance (Outputable id, Outputable pat) =>
596 Outputable (Stmt id pat) where
597 ppr stmt = pprStmt stmt
599 pprStmt (BindStmt pat expr _) = hsep [ppr pat, ptext SLIT("<-"), ppr expr]
600 pprStmt (LetStmt binds) = hsep [ptext SLIT("let"), pprBinds binds]
601 pprStmt (ExprStmt expr _ _) = ppr expr
602 pprStmt (ResultStmt expr _) = ppr expr
603 pprStmt (ParStmt stmtss)
604 = hsep (map (\stmts -> ptext SLIT("| ") <> ppr stmts) stmtss)
605 pprStmt (ParStmtOut stmtss)
606 = hsep (map (\stmts -> ptext SLIT("| ") <> ppr stmts) stmtss)
608 pprDo :: (Outputable id, Outputable pat) => HsDoContext -> [Stmt id pat] -> SDoc
609 pprDo DoExpr stmts = hang (ptext SLIT("do")) 2 (vcat (map ppr stmts))
610 pprDo ListComp stmts = brackets $
611 hang (pprExpr expr <+> char '|')
614 ResultStmt expr _ = last stmts -- Last stmt should
615 quals = init stmts -- be an ResultStmt
618 %************************************************************************
620 \subsection{Enumerations and list comprehensions}
622 %************************************************************************
625 data ArithSeqInfo id pat
626 = From (HsExpr id pat)
627 | FromThen (HsExpr id pat)
629 | FromTo (HsExpr id pat)
631 | FromThenTo (HsExpr id pat)
637 instance (Outputable id, Outputable pat) =>
638 Outputable (ArithSeqInfo id pat) where
639 ppr (From e1) = hcat [ppr e1, pp_dotdot]
640 ppr (FromThen e1 e2) = hcat [ppr e1, comma, space, ppr e2, pp_dotdot]
641 ppr (FromTo e1 e3) = hcat [ppr e1, pp_dotdot, ppr e3]
642 ppr (FromThenTo e1 e2 e3)
643 = hcat [ppr e1, comma, space, ppr e2, pp_dotdot, ppr e3]
645 pp_dotdot = ptext SLIT(" .. ")
649 %************************************************************************
651 \subsection{HsMatchCtxt}
653 %************************************************************************
656 data HsMatchContext id -- Context of a Match or Stmt
657 = DoCtxt HsDoContext -- Do-stmt or list comprehension
658 | FunRhs id -- Function binding for f
659 | CaseAlt -- Guard on a case alternative
660 | LambdaExpr -- Lambda
661 | PatBindRhs -- Pattern binding
662 | RecUpd -- Record update
665 data HsDoContext = ListComp | DoExpr
669 isDoExpr (DoCtxt DoExpr) = True
670 isDoExpr other = False
674 matchSeparator (FunRhs _) = SLIT("=")
675 matchSeparator CaseAlt = SLIT("->")
676 matchSeparator LambdaExpr = SLIT("->")
677 matchSeparator PatBindRhs = SLIT("=")
678 matchSeparator (DoCtxt _) = SLIT("<-")
679 matchSeparator RecUpd = panic "When is this used?"
683 pprMatchContext (FunRhs fun) = ptext SLIT("In the definition of") <+> quotes (ppr fun)
684 pprMatchContext CaseAlt = ptext SLIT("In a case alternative")
685 pprMatchContext RecUpd = ptext SLIT("In a record-update construct")
686 pprMatchContext PatBindRhs = ptext SLIT("In a pattern binding")
687 pprMatchContext LambdaExpr = ptext SLIT("In a lambda abstraction")
688 pprMatchContext (DoCtxt DoExpr) = ptext SLIT("In a 'do' expression pattern binding")
689 pprMatchContext (DoCtxt ListComp) = ptext SLIT("In a 'list comprehension' pattern binding")
691 -- Used to generate the string for a *runtime* error message
692 matchContextErrString (FunRhs fun) = "function " ++ showSDoc (ppr fun)
693 matchContextErrString CaseAlt = "case"
694 matchContextErrString PatBindRhs = "pattern binding"
695 matchContextErrString RecUpd = "record update"
696 matchContextErrString LambdaExpr = "lambda"
697 matchContextErrString (DoCtxt DoExpr) = "'do' expression"
698 matchContextErrString (DoCtxt ListComp) = "list comprehension"